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.
//
// 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));
}
}
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:
Using default toString():
First: HashCodeTest@deadbeef
Second: HashCodeTest@deadbeef
Using System.identityHashCode():
First: 27553328
Second: 4072869

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.

Comments

Thanks so much Roy. It's pretty cleat with your good example and helpful. :)
There exist to be more of the values for the students which they must needed to occupy if they really wanted to get success in the future and favorably these would almost govern better prospects for them.

Popular posts from this blog

The mysterious ORA-03111 error

Note on allocationSize parameter of @SequenceGenerator while using JPA

A note on Java's Calendar set() method