自定义键对象应该是不可变的吗?如果是,那么为什么? [英] Should custom key objects be immutable ?If yes , then why?

查看:64
本文介绍了自定义键对象应该是不可变的吗?如果是,那么为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想将自定义的用户定义对象作为我的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.

  1. 插入密钥,调用hashCode(),分配存储桶
  2. 更改密钥,hashCode更改,不再与存储桶匹配
  3. 通过(新)键查找,hashCode()导致错误的存储桶,未找到值
  4. 通过(旧)键查找,hashCode()导致正确"存储桶,但是现在发现该键不再存在equal(因为它现在是"new"键),因此它也是丢弃
  1. insert key, hashCode() is called, bucket assigned
  2. change key, hashCode changes, no longer matches the bucket
  3. look up by (new) key, hashCode() leads to the wrong bucket, value not found
  4. 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.

这篇关于自定义键对象应该是不可变的吗?如果是,那么为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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