This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashCode same for strings with same values - Why?

 
James Gordon
Ranch Hand
Posts: 106
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dave Landers
Ranch Hand
Posts: 401
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic