java.lang.String 类中私有(private)“哈希”变量的用途是什么。它是私有(private)的,每次调用 hashcode 方法时都会计算/重新计算。
http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java
最佳答案
它用于缓存 hashCode
的String
.因为String
是不可变的,它的 hashCode
永远不会改变,因此在计算完之后尝试重新计算是没有意义的。
在您发布的代码中,它仅在 hash
的值时重新计算。是 0
,如果 hashCode
还没计算或 如果 hashCode
的String
实际上是 0
,这是可能的!
例如,hashCode
的 "aardvark polycyclic bitmap"
是 0
.
Java 13 中似乎已经纠正了这种疏忽,引入了 hashIsZero
。 field :
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 - "hash"字符串类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424530/