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 it's 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.


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.

链接地址: http://www.djcxy.com/p/71624.html

上一篇: 默认的.equals和.hashCode如何为我的类工作?

下一篇: 如何获取重写hashCode()的对象的唯一ID?