不可变的对象和哈希映射键 [英] Immutable objects and hashmap keys

查看:48
本文介绍了不可变的对象和哈希映射键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不可变的对象(除 String 外,例如 Integer 和其他包装类等)是否适合哈希映射键?

Are immutable objects (other than String like Integer and other wrapper classes etc.) good for hashmap keys?

有人可以解释如何做吗?

Can anybody explain how?

推荐答案

如果不可变,则对象的哈希码不会更改,并且可以缓存不同键的哈希码,从而使整个检索过程非常快.同样对于可变对象,hashCode()可能依赖于可能更改的字段,如果发生这种情况,由于hashCode()返回不同的值,您将无法在HashMap中找到键(及其值).

If immutable, the object's hashcode wont change and it allows caching the hashcode of different keys which makes the overall retrieval process very fast. Also for mutable objects ,the hashCode() might be dependent on fields that could change, if this happens you wont be able to find the key (and its value) in the HashMap since hashCode() returns different value.

这篇关于不可变的对象和哈希映射键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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