如何获取覆盖hashCode()的对象的唯一ID? [英] How to get the unique ID of an object which overrides hashCode()?

查看:232
本文介绍了如何获取覆盖hashCode()的对象的唯一ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当Java中的类没有覆盖 hashCode()时,
打印此类的实例会给出一个很好的唯一编号。

When a class in Java doesn't override hashCode(), printing an instance of this class gives a nice unique number.

Object的Javadoc说明 hashCode()

The Javadoc of Object says about hashCode():


尽可能多相当实用,类Object定义的hashCode方法确实为不同的对象返回不同的整数。

但是当类重写时 hashCode(),如何获得
它的唯一编号?

But when the class overrides hashCode(), how can I get it's unique number?

推荐答案

System.identityHashCode(yourObject )将yourObject的'原始'哈希码作为整数给出。唯一性不一定得到保证。 Sun JVM实现将为您提供与此对象的原始内存地址相关的值,但这是一个实现细节,您不应该依赖它。

System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.

编辑:答案修改后汤姆的评论下面重新。内存地址和移动对象。

Answer modified following Tom's comment below re. memory addresses and moving objects.

这篇关于如何获取覆盖hashCode()的对象的唯一ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆