Object.hashCode() 方法中发生了什么?

What happening in Object.hashCode() method?

据我所知 Object.hashCode() 方法有 native 实现。我特别感兴趣:这种方法有没有随机化? 我有 class 直接派生自 Object.class 而没有重新定义 hashCode 方法。如果我错了请纠正我,但是当我们调用 == 运算符时,我们比较此类对象的引用,别名比较哈希码。 所以我们总是得到 false

//pseudocode
new SomeObject(3) == new SomeObject(3)    

因为 Object.hashCode() 方法涉及随机化?

对象 hascode 只是一个 hash,不是指针。所以 == 将比较引用而不是哈希码。

来自spec的hashCode的总契约是:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

关键字 native 告诉实现是使用 JNI(Java 本机接口)在本机代码中完成的。

此外,如果您要覆盖 hashcode 方法,请不要忘记您的实现应满足上述约定,否则您可能会在使用它的地方得到错误的输出。说 HashMap class.

更多信息:What issues should be considered when overriding equals and hashCode in Java?

As far as I know Object.hashCode() class is native.

正确。

I particularly interested in: is there any randomization in this method?

Object.hashCose()返回的哈希码通常基于对象的机器地址在其生命周期的某个时间 .地址和哈希码可能会受到各种随机因素的影响,具体取决于应用程序。

然而,这并不意味着哈希码是随机的。事实上,如果你一个接一个地分配两个对象,并立即得到它们的哈希码,那么很可能这两个哈希码之间会有很强的相关性。

可能...但不能保证。

Correct me if I am wrong but when we call == operator we compare references of such objects.

正确。

... alias compare hashcodes.

如果您说 == 涉及哈希码,那是不正确的。 ==是通过比较对象的当前机器地址来实现的

So do we always get false because of randomization involved into Object.hashCode() method?

没有。在您的示例中,您得到 false 因为对象引用不同!

事实上,两个不同的 Object 实例可能具有相同的哈希码。

  o1 == o2 IMPLIES o1.hashcode() == o2.hashcode()    is TRUE

  o1.hashcode() == o2.hashcode() IMPLIES o1 == o2    is FALSE