Why a trap ?
First ,let's take a look at the comments of this API provided by Sun:
/**
* 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.
*
* @param x object for which the hashCode is to be calculated
* @return the hashCode
* @since JDK1.1
*/
public static native int identityHashCode(Object x);
Pls,pay more and more attention to the default method hashCode() , do you know what is the default method hashCode()?? It is the hashCode() defined in Object class !!!
i.e. the one public native int hashCode(); The most confusing comment is “whether or not the given object's class overrides hashCode()" , this is definitely bullshit bullshit.....
That means if your class overrides hashCode(), System.identityHashCode() != your.hashCode()! Checkout below testcase:
import junit.framework.TestCase;
public class TestIdentityHashCode extends TestCase{
public void testIdentityHahshCodeAlwaysReturnTheSameAsDefaultHashCode()
{
Object arbitaryObj = new Object();
assertEquals(arbitaryObj.hashCode(),System.identityHashCode(arbitaryObj));
ObjectWhichDoesNotOverrideHashCode objUsingDefaultHashCode = new ObjectWhichDoesNotOverrideHashCode();
assertEquals(objUsingDefaultHashCode.hashCode(),System.identityHashCode(objUsingDefaultHashCode));
ObjectWhichOverrideHashCode objUsingOverridedHashCode = new ObjectWhichOverrideHashCode();
assertEquals(objUsingOverridedHashCode.hashCode(),System.identityHashCode(objUsingOverridedHashCode));
}
public void testIdentityHashCodeOfNullIsZero()
{
assertEquals(0, System.identityHashCode(null));
}
private static class ObjectWhichDoesNotOverrideHashCode
{
}
private static class ObjectWhichOverrideHashCode
{
public int hashCode()
{
return 1000;
}
}
}
Above testcase always fails as expected.. so pls pay attention the trap .
BTW: the default hashCode() of Sun's JVM always returns the memory address of the specific Object
which guarantee it's unique. So System.identityHashCode() could be used to generate a unique key
in a same JVM.