The trap of System.identityHashCode()

本文深入探讨了Java中System.identityHashCode方法的工作原理,解释了它如何返回一个对象的默认hashCode值,无论该对象的类是否覆盖了hashCode方法。通过具体示例展示了当类覆盖hashCode方法时,identityHashCode和自定义hashCode之间的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值