2003/12/02 20:23:39
[org.ibex.core.git] / src / org / xwt / util / Hash.java
index 30d07ed..e36f667 100644 (file)
@@ -7,9 +7,10 @@ import java.util.*;
  *  keys, using Radke's quadradic residue linear probing instead of
  *  buckets to minimize object count (less allocations, faster GC).
  *  See C. Radke, Communications of the ACM, 1970, 103-105
+ *
+ *  Not threadsafe.
  */
 public class Hash {
-
     /** this object is inserted as key in a slot when the
      *  corresponding value is removed -- this ensures that the
      *  probing sequence for any given key remains the same even if
@@ -21,7 +22,7 @@ public class Hash {
     private int usedslots = 0;
 
     /** the number of entries with non-null values */
-    private int size = 0;
+    protected int size = 0;
 
     /** when num_slots < loadFactor * size, rehash into a bigger table */
     private final int loadFactor;
@@ -50,13 +51,8 @@ public class Hash {
     }
 
     /** returns all the primary keys in the table */
-    public Object[] keys() {
-        int howmany = 0;
-        for(int i=0; i<vals.length; i++) if (keys1[i] != null) howmany++;
-        Object[] ret = new Object[howmany];
-        int where = 0;
-        for(int i=0; i<vals.length; i++) if (keys1[i] != null) ret[where++] = keys1[i];
-        return ret;
+    public Enumeration keys() {
+        return new HashEnum(this);
     }
 
     public Hash() { this(25, 3); }
@@ -150,6 +146,31 @@ public class Hash {
         vals[dest] = v;
     }
 
+    class HashEnum implements java.util.Enumeration {
+        private final Hash parent;
+        private int iterator = 0;
+        private int found = 0;
+        
+        public HashEnum (Hash parent) { this.parent = parent; }
+        
+        public boolean hasMoreElements() {
+            return found < parent.usedslots;
+        }
+
+        public Object nextElement() {
+            if (!hasMoreElements()) throw new java.util.NoSuchElementException();
+
+            Object o = null;
+            while (o == null) {
+                o = parent.keys1[iterator++];
+            }
+
+            if (o == null) throw new IllegalStateException("Didn't find an element, when I should have.");
+            found++;
+            
+            return o;
+        }
+    }
 }