Optimized HashMap/HashSet and added System.gc() for manual garbage collection invokation
authorstephey <stephey>
Thu, 31 Mar 2011 02:27:46 +0000 (02:27 +0000)
committerstephey <stephey>
Thu, 31 Mar 2011 02:27:46 +0000 (02:27 +0000)
Robust/src/ClassLibrary/HashMap.java
Robust/src/ClassLibrary/HashSet.java
Robust/src/ClassLibrary/System.java

index 158bb253f0727360ab4b3fdde5a85d3452a8bff2..79ecb6d5ea070e837eb447488d5ce8f5154175ce 100644 (file)
@@ -2,6 +2,7 @@ public class HashMap{
   HashEntry[] table;
   float loadFactor;
   int numItems;
+  int threshold;
 
   public HashMap() {
     init(16, 0.75f);
@@ -16,24 +17,31 @@ public class HashMap{
   }
 
   private void init(int initialCapacity, float loadFactor) {
-    table=new HashEntry[initialCapacity];
+    table=new HashEntry[computeCapacity(initialCapacity)];
     this.loadFactor=loadFactor;
     this.numItems=0;
+    this.threshold=(int)(loadFactor*table.length);
+  }
+  
+  private static int computeCapacity(int capacity) {
+      int x=16;
+      while(x<capacity)
+         x=x<<1;
+      return x;
   }
 
   private static int hash(Object o, int length) {
-    if (o==null)
-      return 0;
-    int value=o.hashCode()%length;
-    if (value<0)
-      return -value;
-    return value;
+      int orig=o.hashCode();
+      orig=orig^(orig>>>22)^(orig>>>10);
+      orig=orig^(orig>>>8)^(orig>>4);
+      return orig&(length-1);
   }
 
   void resize() {
-    int newCapacity=2*table.length+1;
+    int newCapacity=table.length<<1;
     HashEntry[] oldtable=table;
     this.table=new HashEntry[newCapacity];
+    this.threshold=(int) (newCapacity*loadFactor);
 
     for(int i=0; i<oldtable.length; i++) {
       HashEntry e=oldtable[i];
@@ -47,6 +55,12 @@ public class HashMap{
     }
   }
 
+    public void clear() {
+       for(int i=0;i<table.length;i++)
+           table[i]=null;
+       numItems=0;
+    }
+
   public boolean isEmpty() {
     return numItems==0;
   }
@@ -108,7 +122,7 @@ public class HashMap{
 
   Object put(Object key, Object value) {
     numItems++;
-    if (numItems>(loadFactor*table.length)) {
+    if (numItems>threshold) {
       //Resize the table
       resize();
     }
index 4145f63610e0d52bf0de6240f93961d153521ce3..4e4a1bcbaa4c9811f2b7218d09edab86a5430e12 100644 (file)
@@ -18,6 +18,9 @@ public class HashSet {
   public boolean isEmpty() {
     return map.isEmpty();
   }
+  public void clear() {
+    map.clear();
+  }
   public boolean contains(Object o) {
     return map.containsKey(o);
   }
index e36beaee47001174b71b275c155fd8d172eeb984..f02562b194531a22106bcaa2ab5e675d642ebd14 100644 (file)
@@ -4,6 +4,8 @@ public class System {
     printString(s);
   }
 
+    public static native void gc();
+
   public static native long currentTimeMillis();
   
   public static native long microTimes();