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-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
13   * </p>
14   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
15   * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
16   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
17   * @param <T> value type
18   */
19  public class CollectionConstraint<T> implements Constraint<T>
20  {
21  
22      /** Acceptable objects. */
23      @SuppressWarnings("checkstyle:visibilitymodifier")
24      protected final Collection<T> objects;
25  
26      /**
27       * Constructor.
28       * @param objects 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      @Override
37      public boolean accept(final T value)
38      {
39          return this.objects.contains(value);
40      }
41  
42      @Override
43      public String failMessage()
44      {
45          return "Value of parameter '%s' is not in the collection of acceptable values.";
46      }
47  
48      /**
49       * Creates a new instance with given objects.
50       * @param objs acceptable objects
51       * @param <T> type
52       * @return new instance with given objects
53       */
54      @SafeVarargs
55      public static <T> CollectionConstraint<T> newInstance(final T... objs)
56      {
57          Collection<T> collection = new LinkedHashSet<>();
58          for (T t : objs)
59          {
60              collection.add(t);
61          }
62          return new CollectionConstraint<>(collection);
63      }
64  
65      @Override
66      public String toString()
67      {
68          return "CollectionConstraint [objects=" + this.objects + "]";
69      }
70  
71  }