问题
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.
- 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
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