How to get the unique ID of an object which overrides hashCode()?
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?
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.
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;
}
}
Maybe this quick, dirty solution will work?
public class A {
static int UNIQUE_ID = 0;
int uid = ++UNIQUE_ID;
public int hashCode() {
return uid;
}
}
This also gives the number of instance of a class being initialized.