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

标签 java caching hashcode effective-java

我有以下来自 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/

相关文章:

java - 当我生成 apk 并安装在我的设备中时,我尝试使用 firebase otp 验证我的手机号码,显示 SHA-1 错误

java - processbuilder java中规定的时间

java - Spring-boot 和 Keycloak 集成

java - 什么时候使用 System.identityhashcode() 和 hashcode() 方法?

java - 为什么选择 31 在 hashcode() 实现中进行乘法运算?

java - 编译器或 JVM 是否强制执行 hashCode/equals 约定?

java - 避免java中许多if else语句的最佳方法

Tomcat 防止静态资源缓存

.net - 无架构数据缓存:NoSQL或其他替代方案?

asp.net - OutputCache 和 RenderAction 缓存整个页面