View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.tokenizer;
12  
13  import java.util.ArrayList;
14  import java.util.Collection;
15  import java.util.Collections;
16  import java.util.Comparator;
17  
18  /**
19   * <code>UniqueList</code> is a successor of <code>java.util.Vector</code> to provide a collection
20   * that contains no duplicate elements, more formally such that e1.compareTo(e2) == 0.
21   *
22   * <p>
23   * The collection is kept ordered whenever elements added or removed and besides uniqueness it is to
24   * provide fast element search based again on e1.compareTo(e2) values.
25   * </p>
26   *
27   * @param <T> the generic type
28   */
29  public class UniqueList<T extends Comparable<? super T>> extends ArrayList<T> {
30  
31    /** The Constant serialVersionUID. */
32    private static final long serialVersionUID = 1L;
33  
34    @Override
35    public synchronized boolean add(T obj) {
36      return add(obj, null);
37    }
38  
39    /**
40     * Adds the.
41     *
42     * @param obj the obj
43     * @param comp the comp
44     *
45     * @return true, if successful
46     */
47    protected synchronized boolean add(T obj, Comparator<? super T> comp) {
48      if (isEmpty()) {
49        return super.add(obj);
50      }
51      int index;
52      index = comp == null ? Collections.binarySearch(this, obj)
53          : Collections.binarySearch(this, obj, comp);
54      if (index < 0) {
55        int insertionPoint = -index - 1;
56        if (insertionPoint >= size()) {
57          super.add(obj);
58        } else {
59          super.add(insertionPoint, obj);
60        }
61      }
62      return index < 0;
63    }
64  
65    @Override
66    public synchronized void add(int index, T obj) {
67      add(obj);
68    }
69  
70    @Override
71    public synchronized boolean addAll(Collection<? extends T> comp) {
72      boolean ok = this != comp;
73      if (ok) {
74        for (T compItem : comp) {
75          ok &= this.add(compItem);
76        }
77      }
78      return ok;
79    }
80  
81  }