java对象id,如何在Java中为每个对象获取唯一ID?

博客讨论了在Java中如何确保对象的唯一标识。作者指出,虽然`Object.hashCode()`通常用于对象的散列,但它不是对象实例的唯一标识符,因为可以被重写。为了解决这个问题,作者推荐使用`System.identityHashCode(obj)`,这个方法返回对象在内存中的身份哈希码,即使`hashCode()`被重写,也能提供唯一的ID。
摘要由CSDN通过智能技术生成

I made a vector set in order to avoid thrashing the GC with iterator allocations and the like

( you get a new/free each for both the set reference and the set iterator for each traversal of a HashSet's values or keys )

anyway supposedly the Object.hashCode() method is a unique id per object. (would fail for a 64 bit version?)

But in any case it is overridable and therefore not guaranteed unique, nor unique per object instance.

If I want to create an "ObjectSet" how do I get a guaranteed unique ID for each instance of an object??

I just found this: which answers it.

解决方案

java.lang.System.identityHashCode(obj); will do this for you, if you really need it and understand the repercussions. It gets the identity hashcode, even if the method to provide the hashcode has been overridden.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值