Thursday, May 8, 2008

Object.hashcode VS System.identityHashCode

basically System.identityHashCode (Object) always returns different values for different objects
Its declared as public static int identityHashCode(Object x)

The hash code for the null reference is zero.

// FileName Test.java
class HashCodeTest
{
int number;
public HashCodeTest(int i)
{ this.number=i;}

public int hashCode() { return this.number; }
}

public class Test
{
public static void main(String[] args)
{
String s1="Namaste"; String s2 = s1;
System.out.println("s1 "+ s1 + " s2 "+ s2);
System.out.println("System.identityHashCode(s1)" + System.identityHashCode(s1));
System.out.println("System.identityHashCode(s2) "+ System.identityHashCode(s2));
s1=s1 + " World";
System.out.println(" s1 "+ s1 + " s2 " + s2);
System.out.println("System.identityHashCode(s1) " + System.identityHashCode(s1));
System.out.println("System.identityHashCode(s2) "+ System.identityHashCode(s2));

HashCodeTest o1 = new HashCodeTest(5);
HashCodeTest o2 = new HashCodeTest(5);

System.out.println("");
System.out.println("First Object : " + o1);
System.out.println("Second Object : " + o2);
System.out.println("System.identityHashCode(First_Object) : " + System.identityHashCode(o1));
System.out.println("System.identityHashCode(Second_Object) : " + System.identityHashCode(o2));
}
}


the output was something like


s1 Namaste s2 Namaste
System.identityHashCode(s1)1671711
System.identityHashCode(s2) 1671711
s1 Namaste World s2 Namaste
System.identityHashCode(s1) 11394033
System.identityHashCode(s2) 1671711

First Object : HashCodeTest@5
Second Object : HashCodeTest@5
System.identityHashCode(First_Object) : 4384790
System.identityHashCode(Second_Object) : 9634993

No comments: