checkpoint
[sbp.git] / src / edu / berkeley / sbp / util / FastSet.java
1 package edu.berkeley.sbp.util;
2 import java.util.*;
3
4 public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T>, Visitable<T> {
5
6     public static final int INITIAL_SIZE = 8;
7
8     private       Object[] array = null;
9     private       T        only  = null;
10     private       int      i     = -1;
11     private       int      size  = 0;
12
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; }
17     public T get(int i) {
18         if (i==0 && only!=null) return only;
19         if (array==null) return null;
20         return (T)array[i];
21     }
22
23     public FastSet() { }
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;
29     }
30
31     public <B,C> void invoke(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);
35     }
36
37     public int size() { return only==null ? size : 1; }
38     private void grow() {
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);
41         array = array2;
42         if (only!=null) {
43             array[size++] = only;
44             only = null;
45         }
46     }
47     public void add(T t, boolean check) {
48         //if (check) for(Object o : this) if (o.equals(t)) return;
49         if (check) {
50             if (only==t) return;
51             if (array != null)
52                 for(int i=0; i<size; i++)
53                     if (array[i]==t) return;
54         }
55         add(t);
56     }
57     public void add(T t) {
58         if (array==null) {
59             if (only!=null) { only = t; return; }
60             grow();
61         } else if (size>=array.length-1) {
62             grow();
63         }
64         array[size++] = t;
65     }
66
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;
71         return false;
72     }
73 }