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 .
Okay I want to have custom user defined objects as keys in my HashMap
Share
If you have a mutable key in a HashMap, then it will end up in the wrong bucket, which totally breaks the Map.
equal(because it is the “new” key now), so it is also discardedIf 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.