Hi, String s1 = new String("hello"); String s2 = new String("hello"); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); How come both have same hashCode? Aren't s1 and s2 two distinct objects, thus having different hashCode. The reason I managed to find out is that s1.equals(s2) but to me they are still different objects! Please comment. Thanks in advance.
Originally posted by James Gordon: The reason I managed to find out is that s1.equals(s2) but to me they are still different objects!
It's because the hashcode is bound to equality, not to object identity. The hashcode even is not *required* to be different for non-equal objects (so an implementation *always* returning the same hashcode for all objects would still be correct, albeit unexpedient); it is only required to be the same for equal objects.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Jul 11, 2001
Originally posted by Dave Landers: If you want to know the object identity, you can use System.identityHashCode(obj). This returns the same thing as Object.hashCode() if it were not overriden.
But even this might theoretically give you the same hashcode for different objects: "It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results." "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects." (http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Object.html) [ October 24, 2002: Message edited by: Ilja Preuss ]