Should custom key objects be immutable ?If yes , then why?

随声附和 提交于 2019-12-13 06:26:16

问题


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 .


回答1:


If you have a mutable key in a HashMap, then it will end up in the wrong bucket, which totally breaks the Map.

  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

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.

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.




回答2:


Yes they should be immutable as they would not function well as keys if they could be changed. Imagine buying a lock and key for your house, but then deciding you'd like to make the key prettier by hammering it into a different shape. It wouldn't work very well, would it? The same principles apply here.




回答3:


Yes. If you update key from somewhere else then you can no longer lookup the value stored for that key.



来源:https://stackoverflow.com/questions/12067475/should-custom-key-objects-be-immutable-if-yes-then-why

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