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?
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
System. identityHashCode() is the method which is used to return the same hash code for any given object that is returned by the default method hashCode(). Also, for every hash code with a null reference zero is returned.
The hashcode() method is a non-final instance method, and should be overridden in any class where the equals(Object) is overridden. By contrast, identityHashCode(Object) is a static method and therefore cannot be overridden.
Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc. An object can also be searched with this unique code.
The answer is no.
System.identityHashCode() simply return the Object.hashCode().
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(). The hash code for the null reference is zero.
While for 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 JavaTM programming language.)
However, there is a bug in Sun JDK indicated that two object can return same hashcode.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With