Why should dictionary keys be immutable?

不想你离开。 提交于 2019-12-17 19:55:31

问题


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

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?


回答1:


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.




回答2:


The dictionary places the items in buckets based on the hash code of the key. If you add an item and then change its key, you can't find the item any more.

If you use the new key value to look for it, the dictionary will look in a different bucket, and if you use the old key value the dictionary will find the bucket where it is, but the key no longer matches.




回答3:


Dictionary types are a mapping between a key and a value. The mapping will use various properties of the key to assign it a slot in the internal dictionary storage. In most cases it simple reduces the properties to an int value.

If a key changes over time then its properties could begin to map to a different index in the table. Hence the key would no longer be able to retrieve values it originally was mapped to in the table. Immutable types avoid this altogether because they can never change. Hence their mapping is consistent for all time



来源:https://stackoverflow.com/questions/15439134/why-should-dictionary-keys-be-immutable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!