1 package edu.berkeley.sbp.util;
4 public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T>, Visitable<T> {
6 public static final int INITIAL_SIZE = 8;
8 private Object[] array = null;
13 public Iterator<T> iterator() { i=0; return this; }
14 public void remove() { throw new Error(); }
15 public boolean hasNext() { return only==null ? i<size : i<1; }
16 public T next() { return only==null ? (T)array[i++] : (i++)==0 ? only : null; }
18 if (i==0 && only!=null) return only;
19 if (array==null) return null;
24 public FastSet(T t) { only = t; }
25 public FastSet(Set<T> s) {
26 if (s.size()==1) { only = s.iterator().next(); return; }
27 array = new Object[s.size()];
28 for(T t : s) array[size++] = t;
31 public <B,C> void visit(Invokable<T,B,C> ivbc, B b, C c) {
32 if (only!=null) ivbc.invoke(only, b, c);
33 else for(int j=0; j<size; j++)
34 ivbc.invoke((T)array[j], b, c);
37 public int size() { return only==null ? size : 1; }
39 Object[] array2 = array==null ? new Object[INITIAL_SIZE] : new Object[array.length * 2];
40 if (array != null) System.arraycopy(array, 0, array2, 0, array.length);
47 public void add(T t, boolean check) {
48 //if (check) for(Object o : this) if (o.equals(t)) return;
52 for(int i=0; i<size; i++)
53 if (array[i]==t) return;
57 public void add(T t) {
59 if (only!=null) { only = t; return; }
61 } else if (size>=array.length-1) {
67 public boolean contains(T t) {
68 if (t==only) return true;
69 if (array==null) return false;
70 for(Object o : array) if (o==t) return true;