According to javadoc System.identityHashCode(Object o) :
Returns the same hash code for this object, which will be returned by the hashCode () method by default, regardless of whether the given class overrides the hashCode () object. The hash code for the null reference is zero.
So, in the first place, System.identityHashCode(nullReference) will always give you 0 instead of nullReference.hashCode() , which will obviously give you a NullPointerException at runtime.
Let us, however, consider the following class:
public class MysteriousOne { @Override public int hashCode() { return 0xAAAABBBB; }
The class overrides hashCode() , which is fine, even if the hash code for each instance is the same, which, however, is not very good if you want to distinguish between the identifiers of several instances. Usually you try to output the .toString() method (which by default gives the class name followed by @ , followed by the hashCode() output), for example, to find out the real identity of the object, but in this case the output will be the same:
MysteriousOne first = new MysteriousOne(); MysteriousOne second = new MysteriousOne(); System.out.println("First: " + first); System.out.println("Second: " + second);
The conclusion will be:
First: MysteriousOne@aaaabbbb Second: MysteriousOne@aaaabbbb
Thus, the existence of such an implementation of hashCode() cannot be distinguished between the identities of several instances. System.identityHashCode() convenient here.
If you do
System.out.println("First: " + System.identityHashCode(first)); System.out.println("Second: " + System.identityHashCode(second));
you will get two different numbers for different instances, even if hashCode() their class implementation returns a constant (in fact, the redefined implementation of hashCode() here will not be called at all, like javadoc):
First: 366712642 Second: 1829164700
In addition, you can pass primitives to System.identityHashCode(Object o) , since they will be placed in the corresponding shells:
int i = 5; System.out.println(System.identityHashCode(i));
Additional Information:
- How do
Object#hashCode() and System#identityHashCode() ?