字符串类如何在Java中缓存Hashcode [英] How does string class does caching of Hashcode in java

查看:38
本文介绍了字符串类如何在Java中缓存Hashcode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Here what is written in String API for Hashcode------
public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

任何人都可以解释这里的缓存如何吗?

一个线索是:---- if(h == 0&& value.length> 0){代码只会进入这种情况,然后才计算哈希码,否则将写入相同的代码.但是,对于使用new这样的新字符串创建的两个字符串,这是怎么发生的:

One clue is :---- if (h == 0 && value.length > 0) { Code will only go inside this condition ,only then hashcode is calculated otherwise same is written.But how this happens for two string created with new like :

String a = new String("abc");字符串b =新的String("abc");请解释一下

String a = new String("abc"); String b = new String("abc"); Please explain it

推荐答案

但是对于使用new这样的新字符串创建的两个字符串,这是怎么发生的:

But how this happens for two string created with new like :

String a = new String("abc"); String b = new String("abc"); 

没有发生.缓存仅针对单个 String 对象发生.

It doesn't happen. Caching only occurs for a single String object.

 int h = hash;
 if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
 }

对于单个 String hash 是哈希代码的存储位置.如果它是 0 ,那么它将对其进行重新计算-将其存储在本地变量 h 中-并在重新计算了哈希代码后,将其重新存储在 hash中,以便将来使用.

For a single String, hash is where the hash code is stored. If it's 0, then it recomputes it -- storing it in the local variable h -- and once the hash code is newly computed, it's stored back in hash so it can be used in the future.

如果 String 是可变的,那么在更改字符串后,存储的哈希码将是错误的,因此,任何更改字符串的方式都必须将 hash 重置为 0 表示必须重新计算.但是,这在许多不同的级别上都是混乱的,这就是为什么 String not 可变的.

If Strings were mutable, then the stored hash code would be wrong after the string got changed, so any way of changing the string would have to reset hash to 0 to indicate it had to be recomputed anew. That gets messy, though, on many many different levels, which is why String is not mutable.

这篇关于字符串类如何在Java中缓存Hashcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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