View Javadoc
1   package org.opentrafficsim.base.parameters.constraint;
2   
3   import java.util.Collection;
4   import java.util.LinkedHashSet;
5   
6   import org.djutils.exceptions.Throw;
7   
8   /**
9    * Constraint that checks whether a value is in a given constraint collection.
10   * <p>
11   * Copyright (c) 2013-2022 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
13   * <p>
14   * @version $Revision$, $LastChangedDate$, by $Author$, initial version 10 sep. 2017 <br>
15   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
16   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
17   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
18   * @param <T> value type
19   */
20  public class CollectionConstraint<T> implements Constraint<T>
21  {
22  
23      /** Acceptable objects. */
24      @SuppressWarnings("checkstyle:visibilitymodifier")
25      protected final Collection<T> objects;
26  
27      /**
28       * @param objects Collection&lt;T&gt;; acceptable objects
29       */
30      public CollectionConstraint(final Collection<T> objects)
31      {
32          Throw.whenNull(objects, "Collection of acceptable objects may not be null.");
33          this.objects = objects;
34      }
35  
36      /** {@inheritDoc} */
37      @Override
38      @SuppressWarnings("checkstyle:designforextension")
39      public boolean accept(final T value)
40      {
41          return this.objects.contains(value);
42      }
43  
44      /** {@inheritDoc} */
45      @Override
46      @SuppressWarnings("checkstyle:designforextension")
47      public String failMessage()
48      {
49          return "Value of parameter '%s' is not in the collection of acceptable values.";
50      }
51  
52      /**
53       * Creates a new instance with given objects.
54       * @param objs T...; acceptable objects
55       * @param <T> type
56       * @return new instance with given objects
57       */
58      @SafeVarargs
59      public static <T> CollectionConstraint<T> newInstance(final T... objs)
60      {
61          Collection<T> collection = new LinkedHashSet<>();
62          for (T t : objs)
63          {
64              collection.add(t);
65          }
66          return new CollectionConstraint<>(collection);
67      }
68  
69      /** {@inheritDoc} */
70      @Override
71      @SuppressWarnings("checkstyle:designforextension")
72      public String toString()
73      {
74          return "CollectionConstraint [objects=" + this.objects + "]";
75      }
76  
77  }