Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

identityHashCode()

 
Nikhil Sun
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hashCode() of two Strings are the same if both the Strings have the same value(Right?).But identityHashCode() is used to check if the Object references of the Strings are the same.What exactly is this identityHashCode().How can it be the same for two objects?If it is computed based on the memory address then my doubt is how can the memory location for an object always be the same?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The identityHashCode() method is for comparing object references for identity. That is, do they point to the same object?

If the identityHashCode() is different, the references definitely do not point to the same object.

If the identityHashCode() is the same, the references probably do point to the same object. But they might not, because you are getting a 32-bit hash code. Obviously, you cannot have different 32-bit hash codes for every possible address in a 64-bit system. But you are not allowed to assume, even on a 32-bit system, that same hash code definitely means identical object.

If you want a definite test of whether object references are identical, use the == operator.
[ October 17, 2006: Message edited by: Peter Chase ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
The identityHashCode() method is for comparing object references for identity. That is, do they point to the same object?


I think this is misleading. Common terminology is actually to call this "object identity". That is, two objects can be equal without being identical.

I've never heard of the term "reference identity".
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nikhil Sun:
If it is computed based on the memory address then my doubt is how can the memory location for an object always be the same?


It might be computed based on the *initial* memory address or something. But that really is an implementation detail that is open to the JVM implementor to decide about.

The important part is that it is guaranteed that the identity hashcode remains the same for an object, not matter what.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic