System.identityHashCode() - What is it?
Today I learnt about a function called System.identityHashCode(). To understand where it is used, let us consider the following program.
//This program overrides the function hashCode() which is perfectly legal. As a result of this, you cannot find out the real identity of the object as it would be printed in the default toString() method. The output turns out to be:
// What will be the output of toString() if we override hashCode() function?
//
public class HashCodeTest {
public int hashCode() { return 0xDEADBEEF; }
public static void main(String[] argv) {
HashCodeTest o1 = new HashCodeTest();
HashCodeTest o2 = new HashCodeTest();
System.out.println("Using default toString():");
System.out.println("First: " + o1);
System.out.println("Second: " + o2);
System.out.println("Using System.identityHashCode():");
System.out.println("First: " + System.identityHashCode(o1));
System.out.println("Second: " + System.identityHashCode(o2));
}
}
Using default toString():Sometimes you might with to print the identity along with your own message, when you override toString() method. In such instances identityHashCode() function comes handy. If you look at the second part of the program output, the identity hash code for both the objects are unique.
First: HashCodeTest@deadbeef
Second: HashCodeTest@deadbeef
Using System.identityHashCode():
First: 27553328
Second: 4072869
Comments