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://tudelft.nl/staff/p.knoppers-1">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       * @param objects Collection&lt;T&gt;; acceptable objects
28       */
29      public CollectionConstraint(final Collection<T> objects)
30      {
31          Throw.whenNull(objects, "Collection of acceptable objects may not be null.");
32          this.objects = objects;
33      }
34  
35      /** {@inheritDoc} */
36      @Override
37      @SuppressWarnings("checkstyle:designforextension")
38      public boolean accept(final T value)
39      {
40          return this.objects.contains(value);
41      }
42  
43      /** {@inheritDoc} */
44      @Override
45      @SuppressWarnings("checkstyle:designforextension")
46      public String failMessage()
47      {
48          return "Value of parameter '%s' is not in the collection of acceptable values.";
49      }
50  
51      /**
52       * Creates a new instance with given objects.
53       * @param objs T...; acceptable objects
54       * @param <T> type
55       * @return new instance with given objects
56       */
57      @SafeVarargs
58      public static <T> CollectionConstraint<T> newInstance(final T... objs)
59      {
60          Collection<T> collection = new LinkedHashSet<>();
61          for (T t : objs)
62          {
63              collection.add(t);
64          }
65          return new CollectionConstraint<>(collection);
66      }
67  
68      /** {@inheritDoc} */
69      @Override
70      @SuppressWarnings("checkstyle:designforextension")
71      public String toString()
72      {
73          return "CollectionConstraint [objects=" + this.objects + "]";
74      }
75  
76  }