aspose file tools*
The moose likes Java in General and the fly likes HashCode same for strings with same values - Why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashCode same for strings with same values - Why?" Watch "HashCode same for strings with same values - Why?" New topic
Author

HashCode same for strings with same values - Why?

James Gordon
Ranch Hand

Joined: Aug 09, 2002
Posts: 106
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.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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
Dave Landers
Ranch Hand

Joined: Jul 24, 2002
Posts: 401
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.
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521


"JavaRanch, where the deer and the Certified play" - David O'Meara
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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 ]
 
jQuery in Action, 2nd edition
 
subject: HashCode same for strings with same values - Why?