PrepZone Logo
PrepZone
Back to Java

Java · Medium

Why must HashMap keys be immutable? What goes wrong if they are mutable?

JavaTrickyCollections

Answer preview

If you mutate fields that affect hashCode(), the entry becomes unreachable. The key's new hash code points to a different bucket, but the entry is still stored in the old bucket.…