gpt4 book ai didi

java - Java中对象的hashcode是如何生成的?

转载 作者:行者123 更新时间:2023-12-02 10:50:36 25 4
gpt4 key购买 nike

在Java中,Object的hashcode值是根据对象的内容通过算法生成的还是根据对象实例内存地址生成的?

最佳答案

如果你查看Java源代码的Object类,它的实现如下:

public native int hashCode();

native hashCode 方法实现取决于 JVM。默认情况下,HotSpot 会根据对象初始内存位置返回随机数,您可以在 source code 中查看它。 (函数 get_next_hash)。

根据 Java docs对于这个方法

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

但是它如何实现 hashCode 方法始终取决于 JVM。

热点jvm中的原生方法实现来生成哈希码:

static inline intptr_t get_next_hash(Thread * Self, oop obj) {
intptr_t value = 0 ;
if (hashCode == 0) {
// This form uses an unguarded global Park-Miller RNG,
// so it's possible for two threads to race and generate the same RNG.
// On MP system we'll have lots of RW access to a global, so the
// mechanism induces lots of coherency traffic.
value = os::random() ;
} else
if (hashCode == 1) {
// This variation has the property of being stable (idempotent)
// between STW operations. This can be useful in some of the 1-0
// synchronization schemes.
intptr_t addrBits = intptr_t(obj) >> 3 ;
value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
} else
if (hashCode == 2) {
value = 1 ; // for sensitivity testing
} else
if (hashCode == 3) {
value = ++GVars.hcSequence ;
} else
if (hashCode == 4) {
value = intptr_t(obj) ;
} else {
// 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.
unsigned t = Self->_hashStateX ;
t ^= (t << 11) ;
Self->_hashStateX = Self->_hashStateY ;
Self->_hashStateY = Self->_hashStateZ ;
Self->_hashStateZ = Self->_hashStateW ;
unsigned v = Self->_hashStateW ;
v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
Self->_hashStateW = v ;
value = v ;
}

关于java - Java中对象的hashcode是如何生成的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32450184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com