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?
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 ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
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".
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
Joined: Jul 11, 2001
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.