字符串类中的“哈希”变量

问题描述 投票:1回答:1

java.lang.String类中私有“哈希”变量的使用是什么。它是私有的,每次调用hashcode方法时都会进行计算/重新计算。

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

java jvm
1个回答
0
投票

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

在您发布的代码中,仅当hash的值为0时才重新计算,如果尚未计算hashCode则可能会发生<hashCode String中的]实际上是0,这是可能的!例如,hashCode"aardvark polycyclic bitmap"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; }

© www.soinside.com 2019 - 2024. All rights reserved.