gpt4 book ai didi

java - 正如 Joshua Bloch 在有效 Java 中所建议的那样,缓存哈希码如何在 Java 中工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:12:02 25 4
gpt4 key购买 nike

我有以下来自 Joshua Bloch 的 effective java 的代码(第 9 项,第 3 章,第 49 页)

If a class is immutable and the cost of computing the hash code is significant, you might consider caching the hash code in the object rather than recalculating it each time it is requested. If you believe that most objects of this type will be used as hash keys, then you should calculate the hash code when the instance is created. Otherwise, you might choose to lazily initialize it the first time hashCode is invoked (Item 71). It is not clear that our PhoneNumber class merits this treatment, but just to show you how it’s done:

    // Lazily initialized, cached hashCode
private volatile int hashCode; // (See Item 71)
@Override public int hashCode() {
int result = hashCode;
if (result == 0) {
result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
hashCode = result;
}
return result;
}

我的问题是这里的缓存(记住 hashCode)是如何工作的。第一次调用hashCode()方法,没有hashCode赋值给result。简要说明此缓存的工作原理会很棒。谢谢

最佳答案

简单。阅读下面我嵌入的评论...

private volatile int hashCode;
//You keep a member field on the class, which represents the cached hashCode value

@Override public int hashCode() {
int result = hashCode;
//if result == 0, the hashCode has not been computed yet, so compute it
if (result == 0) {
result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
//remember the value you computed in the hashCode member field
hashCode = result;
}
// when you return result, you've either just come from the body of the above
// if statement, in which case you JUST calculated the value -- or -- you've
// skipped the if statement in which case you've calculated it in a prior
// invocation of hashCode, and you're returning the cached value.
return result;
}

关于java - 正如 Joshua Bloch 在有效 Java 中所建议的那样,缓存哈希码如何在 Java 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18473071/

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