java Object 中 hashCode 的实现是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13602501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the implementation of hashCode in java Object?
提问by andyqee
Possible Duplicate:
How is hashCode() calculated in Java
可能的重复:
如何在 Java 中计算 hashCode()
I found there's no implementation in hashCode()
method of root class Object
in Java:
我发现在 JavahashCode()
中根类的方法中没有实现Object
:
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.
如果我有 anObject a
和 an Object b
,我怎么知道不使用a.hashCode()
and 的b.hashCode()
值System.out.println()
?只是通过hashCode
实施。
I have try to new
two ArrayList
objects and to my big surprise the hashCode()
values are the same: both of them are 1.
我尝试了new
两个ArrayList
对象,令我惊讶的hashCode()
是它们的值是相同的:它们都是 1。
回答by Kai
hashCode
is a native
method which means that a system library is called internally. See Java Native Interfacefor more details.
hashCode
是一种native
方法,表示在内部调用系统库。有关更多详细信息,请参阅Java 本机接口。
There is a question on SO Why hashCode() and getClass() are native methods?Might be interesting for you.
有一个关于为什么 hashCode() 和 getClass() 是本机方法的问题?可能对你很有趣。
回答by Brian Agnew
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 actualmemory address.
默认的 hashCode 将是特定于实现的。我怀疑它与内存地址有关,但请注意 VM 在内存中移动对象(当然,hashCode 必须保持不变)。所以它不会是实际的内存地址。
回答by Kevin Bowersox
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()
实现经常但并不总是根据对象的内存地址提供一个整数,但是内存地址可以改变。这可能会根据 JVM 实现松散地变化。
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.
哈希码()
如您所知,此方法提供对象的代码。基本上, Object 提供的 hashCode() 的默认实现是通过将内存地址映射到整数值来派生的。如果查看 Object class 的来源,您会发现 hashCode 的以下代码。
公共本机 int hashCode();
说明hashCode是原生实现,一定程度上提供了内存地址。但是,可以覆盖实现类中的 hashCode 方法。