bug report in String.hashCode()

Archie Cobbs archie at whistle.com
Wed Aug 5 11:53:05 PDT 1998


Archie Cobbs writes:
> Godmar Back writes:
> > It seems the string hash method has changed in newer versions of the JDK
> > because the one we still implement in Kaffe is apparently poor.
> > 
> > See http://developer.javasoft.com/developer/bugParade/bugs/4045622.html
> > (needs login)
> > and
> > http://java.sun.com/products/jdk/1.2/compatibility.html
> > (Section Runtime Incompatibilities in Version 1.2, Subsection 3.)
> > 
> > If somebody wants to send a patch that implements the new version,
> > that would be great.
> 
> How's this look.

Wait! forget that previous patch... this one takes advantage of the
immutability of strings...

-Archie

___________________________________________________________________________
Archie Cobbs   *   Whistle Communications, Inc.  *   http://www.whistle.com

Index: String.java
===================================================================
RCS file: /cvs/mod/net/kaffe/libraries/javalib/java/lang/String.java,v
retrieving revision 1.1.1.1.2.2
diff -c -u -r1.1.1.1.2.2 String.java
--- String.java	1998/07/28 17:02:07	1.1.1.1.2.2
+++ String.java	1998/08/05 18:51:17
@@ -22,6 +22,8 @@
 	char[] value;
 	int offset;
 	int count;
+	boolean hashIsValid;
+	int hash;
 
 	/* This is what Sun's JDK1.1 "serialver java.lang.String" spits out */
 	static final long serialVersionUID = -6849794470754667710L;
@@ -226,17 +228,12 @@
 }
 
 public int hashCode() {
-	int i, n=offset+count;
-	int hash = 0;
-
-	if ( count <= 15 ) {
-		for ( i=offset+1; i<n; i++ )
-			hash = (37 * hash) + value[i];
-	}
-	else {
-		int skip = count / 8;
-		for ( i=offset+skip; i<n; i+=skip )
-			hash = (39 * hash) + value[i];
+	if (!hashIsValid) {
+		final int stop = offset + count;
+		for (int index = offset; index < stop; index++) {
+			hash = (31 * hash) + value[index];
+		}
+		hashIsValid = true;
 	}
 	return hash;
 }


More information about the kaffe mailing list