Search code examples
javahash-code-uniqueness

Can I assume two objects with the same System.identityHashCode are the same?


Though two different objects may have the same hash code, however, System.identityHashCode() seems return the memory pointer of the object. I guess there could be no exception in 32-bit JVM implementations, includes Sun JDK, Open JDK. I didn't check the source code, though. In practice, can I assume two objects with the same System.identityHashCode() are the same?


Solution

  • The short answer is no.

    As per the documentation, System.identityHashCode(Object) ...

    Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().

    So then lets check the documentation of Object.hashCode() ...

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)