How to get the unique ID of an object which overrides hashCode()?
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.
hashCode()
method is not for providing a unique identifier for an object. It rather digests the object's state (i.e. values of member fields) to a single integer. This value is mostly used by some hash based data structures like maps and sets to effectively store and retrieve objects.
If you need an identifier for your objects, I recommend you to add your own method instead of overriding hashCode
. For this purpose, you can create a base interface (or an abstract class) like below.
public interface IdentifiedObject<I> {
I getId();
}
Example usage:
public class User implements IdentifiedObject<Integer> {
private Integer studentId;
public User(Integer studentId) {
this.studentId = studentId;
}
@Override
public Integer getId() {
return studentId;
}
}
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.