Java中的对象标识哈希码 [英] object identityhashcode in java
问题描述
我有这个问题.
我一直在我的项目中工作(我也在使用EMF Compare).我需要为正在使用的每个对象保留唯一的ID,这就是为什么我决定使用IdentityHashCode的原因,据我了解,此值在编译过程中是相同的.
I've been working in my project (I'm also using EMF Compare). I need to keep an unique ID for each object that I'm using, that's why I decided to use the IdentityHashCode, as far as I understand, this value is the same through the compilation.
我已经在另一个类的方法中将对象作为参数提供,但是当我尝试获取哈希码时,这与打印对象的值时看到的不一样.
I have given the object as a parameter in the method of another class, but when I try to get the hashcode this is not the same that I can see when I print the value of the object.
类似这样的东西:
System.out.println("The Object is: "+obj)
System.out.println("The hash ID is: +Integer.toHexString(System.identityHashCode(obj)));
但是结果我得到了:
对象是:***xxxxxxxxxxxxxx***.EntityImpl@18e588c (name: Comment) has been removed.
哈希ID为:1ec1758
您可以看到两个值完全不同,但是我不明白为什么.到现在为止,我唯一要做的事情(并且可行)是获取对象的String,然后使用substring方法获取18e588c
(对于本示例)
As you can see the two values are totally different, but I can't understand why. Until now the only thing that I have done (and it works) is to get the String of the object and then use the substring method to get 18e588c
(for this example)
我将不胜感激.
致谢
推荐答案
我需要为正在使用的每个对象保留唯一的ID,这就是为什么我决定使用IdentityHashCode的原因,据我了解,此值在编译过程中是相同的.
I need to keep an unique ID for each object that I'm using, that's why I decided to use the IdentityHashCode, as far as I understand, this value is the same through the compilation.
不.它与编译无关,并且不保证是唯一的.
No. It's got nothing to do with compilation, and it's not guaranteed to be unique.
目前尚不清楚您要做什么,但是您根本不应该将哈希码视为唯一的-不能保证它们是唯一的.
It's not clear what you're trying to do, but you simply shouldn't regard hash codes as unique - they're not guaranteed to be.
Object.hashCode
文档指定:
在合理可行的范围内,由Object类定义的hashCode方法确实为不同的对象返回不同的整数.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.
那与保证它不一样.
您也 被调用toString()
的结果所迷惑-我怀疑您的类实际上覆盖了hashCode()
,并且Object.toString()
调用了可能被覆盖的hashCode()
方法,而不是使用身份哈希码:
You're also being confused by the result of calling toString()
- I suspect your class actually overrides hashCode()
, and Object.toString()
calls the potentially-overridden hashCode()
method rather than using the identity hash code:
Object类的toString方法返回一个字符串,该字符串包括该对象是其实例的类的名称,符号符'@'和该对象的哈希码的无符号十六进制表示形式.换句话说,此方法返回的字符串等于:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
如果调用obj.hashCode()
,您将看到与toString
相同的值.
If you call obj.hashCode()
you'll see the same value that's shown by toString
.
这篇关于Java中的对象标识哈希码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!