[Spread-users] Bug in Spread Java interface (w/patch)

Leonard leonardr at laswell.sp.collab.net
Fri Aug 17 14:50:32 EDT 2001


Greetings all,

Enclosed are patches for GroupID.java and SpreadGroup.java which fix a
small but annoying bug.

Background
----------

For any objects foo and bar, if foo.equals(bar) is true, then Java
requires that foo.hashCode() equal bar.hashCode(). This requirement is
stated here:

http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#hashCode()

GroupID and SpreadGroup implement equals(), but use Object's default
hashCode() implementation, which tries as hard as it can to return
different hash codes for distinct objects (generally it uses an object's
address). If foo and bar are different instances of the same SpreadGroup,
then foo.equals(bar) will return true but foo.hashCode() will not equal
bar.hashCode().

The main manifestation of this bug is when you store something in a
Hashtable keyed to some object, and then can't get it out later using a
different instance of the same object as the key.

The fix
-------

I implemented a hashCode() for SpreadGroup which hashes on the string
representation of the group, and a hashCode() for GroupID which hashes on
the internal representation of the ID. I have tested the SpreadGroup
patch, but my code never makes use of GroupID so I haven't tested that
patch beyond making sure it compiles (there's no reason why it shouldn't
work, though).

The patches
-----------

--- orig/java/splib_src/GroupID.java	Fri Jun 22 10:57:50 2001
+++ java/splib_src/GroupID.java	Fri Aug 17 02:31:04 2001
@@ -104,6 +104,18 @@
 		return ID;
 	}

+	// Returns the hash code of the group ID.
+	///////////////////////////////////////////////////////////////////
+	/**
+	 * Returns the hash code of the group ID.
+	 *
+	 * @return int the hash code
+	 */
+	public int hashCode()
+	{
+		return ID.hashCode();
+	}
+
 	// Converts the group ID to a string.
 	/////////////////////////////////////
 	/**


--- orig/java/splib_src/SpreadGroup.java	Fri Jun 22 10:57:50 2001
+++ java/splib_src/SpreadGroup.java	Fri Aug 17 04:16:54 2001
@@ -237,4 +237,18 @@
 		///////////////////////////////////////////
 		return true;
 	}
+
+	// Returns the hash code of the group, which is defined as the
+	// hash code of its name.
+	///////////////////////////////////////////////////////////////////
+	/**
+	 * Returns the hash code of the group, which is defined as the
+	 * hash code of its name.
+	 *
+	 * @return int the hash code
+	 */
+	public int hashCode()
+	{
+		return toString().hashCode();
+	}
 }

I hope you find these patches useful.

--
Leonard Richardson  | CollabNet
leonardr at collab.net | http://www.collab.net/
"Duty now for the future"






More information about the Spread-users mailing list