What's the implementation of hashCode in java Object? [duplicate]

*爱你&永不变心* 提交于 2019-11-27 23:46:42

问题


Possible Duplicate:
How is hashCode() calculated in Java

I found there's no implementation in hashCode() method of root class Object in Java:

public native int hashCode(); 

If I have an Object a and an Object b, how can I know the a.hashCode() and b.hashCode() value without using System.out.println()? Just by the hashCode implementation.

I have try to new two ArrayList objects and to my big surprise the hashCode() values are the same: both of them are 1.


回答1:


hashCode is a native method which means that a system library is called internally. See Java Native Interface for more details.

There is a question on SO Why hashCode() and getClass() are native methods? Might be interesting for you.




回答2:


The default hashCode is going to be implementation-specific. I suspect it's related to the memory address, but note that the VM moves objects around in memory (and, of course, the hashCode has to remain the same). So it won't be the actual memory address.




回答3:


The default hashcode() implementation frequently but not always provides an integer based loosely on the memory address of the object, however the memory address can change. This may vary based loosely upon the JVM implementation.

hashCode()

As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode.

public native int hashCode();

It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.

http://www.javaworld.com/community/node/1006



来源:https://stackoverflow.com/questions/13602501/whats-the-implementation-of-hashcode-in-java-object

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