本文介绍了如何获取覆盖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():

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

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

推荐答案

将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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 06:17