views:

2668

answers:

2

Hello!

When a class in Java doesn't override hashCode(), printing an instance of this class gives a nice unique number.

The Javadoc of Object says about hashCode():

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.

But when the class overrides hashCode(), how can I get it's unique number?

+20  A: 

System.identityHashCode() will get you the 'original' hash code. Uniqueness isn't necessarily guaranteed, note. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.

EDIT: Answer modified following Tom's comment below re. memory addresses and moving objects.

Brian Agnew
Whoa, I never knew that. Thanks for sharing. :)
Emil H
+1 Good knowledge! Hadn't heard of that before either
Harry Lime
Let me guess: it's not unique, when you have more than 2**32 objects in same JVM? ;) Can you point me to some place, where the non-uniqueness it is described? Thanx!
ivan_ivanovich_ivanoff
It doesn't matter how many objects there are, or how much memory there is. Neither hashCode() nor identityHashCode() is required to produce a unique number.
Alan Moore
Brian: It's not the actual memory location, you happen to get a rehashed version of an address when first computed. In a modern VM objects will move about in memory.
Tom Hawtin - tackline
Thanks Tom. I will edit appropriately
Brian Agnew
+8  A: 

The javadoc for Object specifies that

This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.

If a class overrides hashCode, it means that it wants to generate a specific id, which will (one can hope) have the right behaviour.

You can use System.identityHashCode to get that id for any class.

Valentin Rocher