java - String 类中的 "hash"变量

标签 java jvm

java.lang.String 类中私有(private)“散列”变量的用途是什么。它是私有(private)的,每次调用 hashcode 方法时都会计算/重新计算。

http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java

最佳答案

用于缓存StringhashCode。因为 String 是不可变的,它的 hashCode 永远不会改变,所以在它已经被计算之后试图重新计算它是没有意义的。

在您发布的代码中,只有当 hash 的值为 0 时才会重新计算,这可能发生在 hashCode 还没有计算或者如果StringhashCode实际上是0,这是有可能的!

例如"aardvark polycyclic bitmap"hashCode0

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/

相关文章:

java - 使用 SAX 解析器遍历 xml 文档并以所需格式打印输出

java - JVM突然崩溃

java - DeleteOnExit jvm 关闭

java - 在子类中使用 super 或 this 访问父类(super class)中的属性?

java - Java 中的 Spark 自定义分区

java - 如何在 jvm 中创建超过 Integer.MAX_VALUE 的对象?

java.lang.UnsupportedClassVersionError : com/google/doclava/Doclava : Unsupported major. 次要版本 51.0 android build

java - .c文件那个 "starts"的JVM?

java - 如何保留我设置的值以便可以返回它?安卓

java - 如何实现模拟功能?