Home | History | Annotate | Download | only in collect
      1 /*
      2  * Copyright (C) 2007 The Guava Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.collect;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 
     21 /**
     22  * A constraint that an element must satisfy in order to be added to a
     23  * collection. For example, {@link Constraints#notNull()}, which prevents a
     24  * collection from including any null elements, could be implemented like this:
     25  * <pre>   {@code
     26  *
     27  *   public Object checkElement(Object element) {
     28  *     if (element == null) {
     29  *       throw new NullPointerException();
     30  *     }
     31  *     return element;
     32  *   }}</pre>
     33  *
     34  * <p>In order to be effective, constraints should be deterministic; that is,
     35  * they should not depend on state that can change (such as external state,
     36  * random variables, and time) and should only depend on the value of the
     37  * passed-in element. A non-deterministic constraint cannot reliably enforce
     38  * that all the collection's elements meet the constraint, since the constraint
     39  * is only enforced when elements are added.
     40  *
     41  * @author Mike Bostock
     42  */
     43 @GwtCompatible
     44 interface Constraint<E> {
     45   /**
     46    * Throws a suitable {@code RuntimeException} if the specified element is
     47    * illegal. Typically this is either a {@link NullPointerException}, an
     48    * {@link IllegalArgumentException}, or a {@link ClassCastException}, though
     49    * an application-specific exception class may be used if appropriate.
     50    *
     51    * @param element the element to check
     52    * @return the provided element
     53    */
     54   E checkElement(E element);
     55 
     56   /**
     57    * Returns a brief human readable description of this constraint, such as
     58    * "Not null" or "Positive number".
     59    */
     60   @Override
     61   String toString();
     62 }
     63