java.lang.String 类中私有(private)“散列”变量的用途是什么。它是私有(private)的,每次调用 hashcode 方法时都会计算/重新计算。
最佳答案
用于缓存String
的hashCode
。因为 String
是不可变的,它的 hashCode
永远不会改变,所以在它已经被计算之后试图重新计算它是没有意义的。
在您发布的代码中,只有当 hash
的值为 0
时才会重新计算,这可能发生在 hashCode
还没有计算或者如果String
的hashCode
实际上是0
,这是有可能的!
例如"aardvark polycyclic bitmap"
的hashCode
为0
。
Java 13 似乎已通过引入 hashIsZero
字段纠正了这种疏忽:
public int hashCode() {
// The hash or hashIsZero fields are subject to a benign data race,
// making it crucial to ensure that any observable result of the
// calculation in this method stays correct under any possible read of
// these fields. Necessary restrictions to allow this to be correct
// without explicit memory fences or similar concurrency primitives is
// that we can ever only write to one of these two fields for a given
// String instance, and that the computation is idempotent and derived
// from immutable state
int h = hash;
if (h == 0 && !hashIsZero) {
h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
if (h == 0) {
hashIsZero = true;
} else {
hash = h;
}
}
return h;
}
关于java - String 类中的 "hash"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424530/