字典键为什么应该是一成不变的? [英] Why should dictionary keys be immutable?

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

问题描述

有一个关于他们为什么要求使用不可变对象作为字典键的问题。

Got a question about why they ask to use immutable objects as keys in a Dictionary.

这个问题实际上得到了我的头,当我最近使用的字典(不对于一个哈希表的真正目的显然虽然)放置XML节点对象作为键。然后,我在使用过程中多次更新的节点。

The question actually got in my head when I recently used a dictionary (not for the very purpose of a Hash table apparently though) to place Xml Node objects as keys. I then updated the nodes several times during the usage.

那么,是什么使用一成不变的键究竟意味着什么?

So what does 'use immutable keys' really mean?

推荐答案

当你插入一个关键到一个哈希表,哈希表要求其散列码的钥匙,并记住它与密钥本身和相关的值一起。当你以后执行查找,哈希表会询问你的关键的寻找的为它的散列码,并且可以非常迅速地找到有相同的散列码表的所有键。

When you insert a key into a hash table, the hash table asks the key for its hash code, and remembers it along with the key itself and the associated value. When you later perform a lookup, the hash table asks the key you're looking for for its hash code, and can very quickly find all the keys in the table that have the same hash code.

这是所有罚款,只要在哈希表中的键保持相同的散列码在他们的生活 - 但如果他们的可变的(并且是插入到哈希表),那么通常的哈希码将会改变后发生突变,此时,当您搜索它的进入将永远不会被发现。

That's all fine so long as the keys in the hash table keep the same hash code throughout their lives - but if they're mutable (and are mutated after being inserted into the hash table) then typically the hash code will change, at which point the entry will never be found when you search for it.

当然,这仅适用于影响平等突变。例如,如果你哈希的名称和生日实体,但由于某些原因只有名称用于平等(和计算时,因此,只有名称已使用哈希代码),那么你可以插入成一个哈希表作为重点,改变它的生日,仍然能够再次与没有问题后查找。

Of course, this only applies to mutations which affect equality. For example, if you hash a Person entity with a name and birthday, but for some reason only the name is used for equality (and thus only the name is used when computing the hash code) then you could insert a Person into a hash table as a key, change its birthday, and still be able to look it up again later with no problems.

这篇关于字典键为什么应该是一成不变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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