HashMap值需要是不可变的吗? [英] Do HashMap values need to be immutable?

查看:244
本文介绍了HashMap值需要是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道HashMap中的键需要是不可变的,或至少确保他们的哈希码( hashCode())不会改变或与另一个对象冲突不同的状态。



但是,存储在HashMap中的值需要与上面相同*?为什么或为什么不?



*这个想法是能够改变值(如调用setter),而不影响以后从HashMap使用不可变键。如果值发生了变化,可以断开与键的关联?



我的问题主要是关于Java,欢迎其他语言。

解决方案

RE:如果值发生了变化,



地图返回给定键的对象引用。

该键将始终指向同一对象引用。以某种方式更改对象(即更改其实例变量)将影响检索该对象的能力。


I understand that keys in a HashMap need to be immutable, or at least ensure that their hash code (hashCode()) will not change or conflict with another object with different state.

However, do the values stored in HashMap need to be the same as above*? Why or why not?

* The idea is to be able to mutate the values (such as calling setters on it) without affecting the ability to retrieve them later from the HashMap using immutable keys. If values are mutated, can that break their association to the keys?

My question is mainly concerning Java, however, answers for other languages are welcome.

解决方案

RE: If values are mutated, can that break their association to the keys?.

No.

A Map returns an object reference given a key. That key will alway point to the same object reference. Changing the object in some way (i.e. changing its instance variables) will not affect the ability to retrieve that object.

这篇关于HashMap值需要是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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