Patch: java.util.Hashtable, java.util.HashMap

Jeff Sturm jsturm@detroit.appnet.com
Sat Dec 16 23:08:00 GMT 2000


The rehash() method will corrupt a Hashtable during put() if the bucket
isn't empty.  The reason is that `idx' is recomputed after rehash(), but
not `last'.

A simple fix is elimination of the `last' variable, since it is as
equally correct to link to the head of the list as to the tail.

The fix applies identically to Hashtable and HashMap.

2000-11-17  Jeff Sturm  <jeff.sturm@commerceone.com>

	* java/util/Hashtable.java (put): Remove `last' variable.
	Link new entry to head of list.
	* java/util/HashMap.java (put): Ditto.

Index: HashMap.java
===================================================================
RCS file: /cvs/gcc/gcc/libjava/java/util/HashMap.java,v
retrieving revision 1.2
diff -u -r1.2 HashMap.java
--- HashMap.java	2000/12/11 03:47:47	1.2
+++ HashMap.java	2000/12/17 06:55:36
@@ -297,7 +297,6 @@
     modCount++;
     int idx = hash(key);
     Entry e = buckets[idx];
-    Entry last = e; // Final entry in bucket's linked list, if any.
     
     while (e != null)
       {
@@ -309,7 +308,6 @@
 	  }
 	else
 	  {
-	    last = e;
 	    e = e.next;
 	  }
       }
@@ -324,10 +322,8 @@
 
     e = new Entry(key, value);
     
-    if (last != null)
-      last.next = e;
-    else
-      buckets[idx] = e;
+    e.next = buckets[idx];
+    buckets[idx] = e;
     
     return null;
   }
Index: Hashtable.java
===================================================================
RCS file: /cvs/gcc/gcc/libjava/java/util/Hashtable.java,v
retrieving revision 1.8
diff -u -r1.8 Hashtable.java
--- Hashtable.java	2000/12/11 04:54:55	1.8
+++ Hashtable.java	2000/12/17 06:55:36
@@ -295,7 +295,6 @@
     modCount++;
     int idx = hash(key);
     HashMap.Entry e = buckets[idx];
-    HashMap.Entry last = e; // Final entry in bucket's linked list, if
any.
     
     // Hashtable does not accept null values. This method doesn't
dereference 
     // `value' anywhere, so check for it explicitly.
@@ -312,7 +311,6 @@
 	  }
 	else
 	  {
-	    last = e;
 	    e = e.next;
 	  }
       }
@@ -327,10 +325,8 @@
 
     e = new Entry(key, value);
     
-    if (last != null)
-      last.next = e;
-    else
-      buckets[idx] = e;
+    e.next = buckets[idx];
+    buckets[idx] = e;
     
     return null;
   }


More information about the Java-patches mailing list