Java.lang.Object的hashCode算法究竟是什么?

10
JVM中用于实现java.lang.Object隐式hashCode()方法的算法是什么?答案偏向于使用OpenJDKOracle JDK

7
可能的事实是这是一种“本地”的方法,而且不多人知道在哪里找到它的实现。 - Pshemo
2
请参阅https://dev59.com/b2Ml5IYBdhLWcg3w96-L,其中包含对本地源的链接。但是,在阅读源代码后,我感到更加困惑了。 - user2864740
值得注意的是,其他对象的哈希码算法都五花八门。字符串最后我查看时使用的是字符串数据前N个字符的哈希值。容器对象将使用包含对象的哈希之和的某种形式。 - Hot Licks
已经注意到了。我理解,但我仍然对特定的对象很感兴趣。 - djhaskin987
1个回答

8
实现方式取决于具体情况(且非常依赖实现,只要一致即可)。然而,根据这里的答案,您可以查看在OpenJDK 7中生成哈希值的本地源文件(查看get_next_hash()函数),该版本实际上指定了许多可能的算法。
// Possibilities:
// * MD5Digest of {obj,stwRandom}
// * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
// * A DES- or AES-style SBox[] mechanism
// * One of the Phi-based schemes, such as:
//   2654435761 = 2^32 * Phi (golden ratio)
//   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
// * A variation of Marsaglia's shift-xor RNG scheme.
// * (obj ^ stwRandom) is appealing, but can result
//   in undesirable regularity in the hashCode values of adjacent objects
//   (objects allocated back-to-back, in particular).  This could potentially
//   result in hashtable collisions and reduced hashtable efficiency.
//   There are simple ways to "diffuse" the middle address bits over the
//   generated hashCode values
//

如前所述, 默认算法是使用随机数,但是下面有一个有趣的评论提到:

// Marsaglia's xor-shift scheme with thread-specific state
// This is probably the best overall implementation -- we'll
// likely make this the default in future releases.

这类似于上述可能性列表中提到的(obj ^ stwRandom)方法,但它通过将“线程特定状态”信息绑定到哈希中来避免了与快速连续分配对象相关的不必要规律性 - 因此,如果由于在两个并行执行的线程上分配了两个非常相似的时间而分配了两个对象,则馈入哈希的离散线程信息应确保生成足够离散的哈希。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接