Java对象的地址值(identityHashCode(Object x)、hashCode()区别)

Java中的Object.hashCode()默认基于内存地址,但可重写,不保证与内存地址对应。而System.identityHashCode(Object x)始终返回对象的内存地址,不受重写影响。当需要判断对象是否指向同一内存地址时,应使用System.identityHashCode()。测试示例显示,即使两个对象属性相同(克隆实例),hashCode可能相同,但identityHashCode不同。
摘要由CSDN通过智能技术生成

Object的hashCode()默认是返回内存地址的,但是hashCode()可以重写,所以hashCode()不能代表内存地址的不同

System.identityHashCode(Object x)方法可以返回对象的内存地址,不管该对象的类是否重写了hashCode()方法。

  • 首先看一下System.identityHashCode(Object x)方法的源码:
/**
     * 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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值