optimizations to FastSet: make it final again, don't shift the contents of the entire...
[sbp.git] / src / edu / berkeley / sbp / util / FastSet.java
index bdfa380..289e5ec 100644 (file)
@@ -1,7 +1,9 @@
+// Copyright 2006-2007 all rights reserved; see LICENSE file for BSD-style license
+
 package edu.berkeley.sbp.util;
 import java.util.*;
 
-public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T> {
+public final class FastSet<T> implements Iterator<T>, Iterable<T>, Visitable<T> {
 
     public static final int INITIAL_SIZE = 8;
 
@@ -20,6 +22,12 @@ public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T> {
         return (T)array[i];
     }
 
+    public T first() {
+        if (only != null) return only;
+        if (array != null) return (T)(array[0]);
+        return null;
+    }
+
     public FastSet() { }
     public FastSet(T t) { only = t; }
     public FastSet(Set<T> s) {
@@ -28,6 +36,30 @@ public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T> {
         for(T t : s) array[size++] = t;
     }
 
+    public void remove(T t) {
+        if (only != null) {
+            if (only==t) only=null;
+            return;
+        }
+        boolean found = false;
+        int j;
+        for(j=0; j<size; j++)
+            if (array[j]==t) {
+                found = true;
+                break;
+            }
+        if (!found) return;
+        array[j] = array[size-1];
+        array[size-1] = null;
+        size--;
+    }
+
+    public <B,C> void visit(Invokable<T,B,C> ivbc, B b, C c) {
+        if (only!=null) ivbc.invoke(only, b, c);
+        else for(int j=0; j<size; j++)
+                 ivbc.invoke((T)array[j], b, c);
+    }
+
     public int size() { return only==null ? size : 1; }
     private void grow() {
         Object[] array2 = array==null ? new Object[INITIAL_SIZE] : new Object[array.length * 2];
@@ -40,7 +72,12 @@ public /*final*/ class FastSet<T> implements Iterator<T>, Iterable<T> {
     }
     public void add(T t, boolean check) {
         //if (check) for(Object o : this) if (o.equals(t)) return;
-        if (check) for(Object o : this) if (o==t) return;
+        if (check) {
+            if (only==t) return;
+            if (array != null)
+                for(int i=0; i<size; i++)
+                    if (array[i]==t) return;
+        }
         add(t);
     }
     public void add(T t) {