HashMap值需要是不可变的吗? [英] Do HashMap values need to be immutable?
问题描述
我知道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屋!