Joshua Bloch在有效的java中建议如何在Java中使用缓存哈希码? [英] how caching hashcode works in Java as suggested by Joshua Bloch in effective java?

查看:143
本文介绍了Joshua Bloch在有效的java中建议如何在Java中使用缓存哈希码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following piece of code from effective java by Joshua Bloch (Item 9, chapter 3, page 49)


如果a class是不可变的,并且计算哈希代码的成本是
很重要,您可以考虑在对象
中缓存哈希代码,而不是每次请求时重新计算它。如果您认为
将此类型的大多数对象用作哈希键,那么
应该在创建实例时计算哈希码。
否则,您可能会在第一次调用
hashCode时选择懒惰地初始化它(第71项)。目前尚不清楚我们的PhoneNumber
类是否值得这样做,只是为了向您展示它是如何完成的:

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 将其分配给结果。关于这种缓存如何工作的简要说明。
谢谢

my question is how the caching (remembering the hashCode) works here. The very first time, hashCode() method is called, there is no hashCode to assign it to result. a brief explanation on how this caching works will be great. Thanks

推荐答案

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

Simple. Read my embedded comments below...

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;
   }

这篇关于Joshua Bloch在有效的java中建议如何在Java中使用缓存哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆