问题描述
好吧,我想将自定义的用户定义对象作为我的HashMap
中的键,而不是说String
.候选对象应该是不可变的吗?我在某处读到,最佳实践是使它们不变,但是我自己却找不到原因.
Okay I want to have custom user defined objects as keys in my HashMap
instead of say String
. Should the candidate objects be immutable ? I read somewhere that the best practice is to make them immutable but I can not figure out the reason myself .
推荐答案
如果HashMap中有可变键,则它将以错误的存储桶结尾,从而完全破坏了地图.
If you have a mutable key in a HashMap, then it will end up in the wrong bucket, which totally breaks the Map.
- 插入密钥,调用hashCode(),分配存储桶
- 更改密钥,hashCode更改,不再与存储桶匹配
- 通过(新)键查找,hashCode()导致错误的存储桶,未找到值
- 通过(旧)键查找,hashCode()导致正确"存储桶,但是现在发现该键不再存在
equal
(因为它现在是"new"键),因此它也是丢弃
- insert key, hashCode() is called, bucket assigned
- change key, hashCode changes, no longer matches the bucket
- look up by (new) key, hashCode() leads to the wrong bucket, value not found
- look up by (old) key, hashCode() leads to the "correct" bucket, but now the key found there is no longer
equal
(because it is the "new" key now), so it is also discarded
如果TreeMap中有可变键,则它将最终在树的错误位置结束,该树应该被排序(并且发生在插入时).基本上与上述相同.
If you have a mutable key in a TreeMap, then it will end up in the wrong position of the tree, which is supposed to be sorted (and that happens at insertion-time). Basically same flow as above.
由于我们喜欢在这里使用比喻,所以这就好比在现有电话簿中使用魔术笔更改您的名字而无需打印整本新书一样:因此,您的新名字史密斯"仍将列在约翰"和约翰斯顿"之间(没有人会寻找它),也没有人会在"Smart"和"Smithers"(他们正在寻找它的地方)之间找到它. TreeMap的工作方式就像电话簿一样.
And since we like similes around here, this is like changing your name in an existing phonebook with a magic marker without printing a whole new book: So your new name "Smith" will still be listed between "John" and "Johnston" (where no one will look for it), and no one will find it between "Smart" and "Smithers" (where they are looking for it). TreeMap works just like a phonebook.
这篇关于自定义键对象应该是不可变的吗?如果是,那么为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!