为什么哈希图中的不可变对象如此有效? [英] Why are immutable objects in hashmaps so effective?

查看:23
本文介绍了为什么哈希图中的不可变对象如此有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我了解了 HashMap.有人注意到:

So I read about HashMap. At one point it was noted:

不变性还允许缓存不同键的哈希码,这使得整个检索过程非常快,并且表明 Java Collection API 提供的 String 和各种包装类(例如,Integer)非常好HashMap 键."

"Immutability also allows caching the hashcode of different keys which makes the overall retrieval process very fast and suggest that String and various wrapper classes (e.g., Integer) provided by Java Collection API are very good HashMap keys."

我不太明白……为什么?

I don't quite understand... why?

推荐答案

String#hashCode:

private int hash;

...

public int hashCode() {
    int h = hash;
    if (h == 0 && count > 0) {
        int off = offset;
        char val[] = value;
        int len = count;

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

由于 String 的内容永远不会改变,类的创建者选择在计算一次后缓存哈希.这样,就不会浪费时间重新计算相同的值.

Since the contents of a String never change, the makers of the class chose to cache the hash after it had been calculated once. This way, time is not wasted recalculating the same value.

这篇关于为什么哈希图中的不可变对象如此有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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