View Javadoc

1   /*
2    *  Copyright 2001-2004 The Apache Software Foundation
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  package net.sf.collections15.functors.predicate;
17  
18  import net.sf.collections15.Predicate;
19  
20  import java.io.Serializable;
21  import java.util.HashSet;
22  import java.util.Set;
23  
24  /***
25   * <code>Predicate</code> implementation that returns <code>true</code> the
26   * first time any given object is evaluated by the <code>Predicate</code>, and
27   * returns <code>false</code> every time the same object is subsequently
28   * evaluated</code>.
29   *
30   * @author Stephen Colebourne
31   * @author Chris Lambrou (port to Java 5.0)
32   * @since Collections15 1.0
33   */
34  public final class UniquePredicate <E> implements Predicate<E>, Serializable
35  {
36  
37      static final long serialVersionUID = 5170814862386683025L;
38  
39      /***
40       * The set of previously evaluated objects.
41       */
42      private final Set<E> evaluatedObjects = new HashSet<E>();
43  
44      /***
45       * Creates and returns a new <code>UniquePredicate</code> instance.
46       *
47       * @return A new <code>UniquePredicate</code> instance.
48       */
49      public static <T> Predicate<T> getInstance()
50      {
51          return new UniquePredicate<T>();
52      }
53  
54      /***
55       * Creates a new <code>UniquePredicate</code> instance.
56       */
57      protected UniquePredicate()
58      {
59      }
60  
61      /***
62       * Evaluates the <code>Predicate</code> returning <code>true</code> only if
63       * the input object hasn't been previously evaluated by this
64       * <code>Predicate</code>.
65       *
66       * @param object The input object to evaluate.
67       *
68       * @return <code>true</code> if this is the first time the object has been
69       *         evaluated by this <code>Predicate</code>. <code>false</code> if
70       *         the opject has ben previously evaluated by this
71       *         <code>Predicate</code>.
72       */
73      public boolean evaluate(E object)
74      {
75          return evaluatedObjects.add(object);
76      }
77  
78  }