Should custom key objects be immutable ?If yes , then why?
问题 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,