How to get the unique ID of an object which overrides hashCode()?

ivan_ivanovich_ivanoff picture ivan_ivanovich_ivanoff · May 26, 2009 · Viewed 216.9k times · Source

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 its unique number?

Answer

Brian Agnew picture Brian Agnew · May 26, 2009

System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. 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.