object identityhashcode in java

微笑、不失礼 提交于 2020-06-27 04:23:07

问题


I've got this question.

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.

Something like this:

System.out.println("The Object is: "+obj)

System.out.println("The hash ID is: +Integer.toHexString(System.identityHashCode(obj)));

But as a result I get this:

The Object is : ***xxxxxxxxxxxxxx***.EntityImpl@18e588c (name: Comment) has been removed.

The hash ID is: 1ec1758

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)

I'd appreciate any answer.

Regards


回答1:


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.

The Object.hashCode documentation specifies:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.

That's not the same thing as guaranteeing it though.

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:

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())

If you call obj.hashCode() you'll see the same value that's shown by toString.



来源:https://stackoverflow.com/questions/17235132/object-identityhashcode-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!