17 / 17

Why is it bad to use a mutable object as a key in a HashMap?

Difficulty: 4/10

Mutable HashMap Keys

A mutable object is dangerous as a HashMap key when its fields used by equality or hashing can change after insertion. If the object's hash code changes, the HashMap may search for it in a different bucket than the one where the entry was originally stored, making the value difficult or impossible to retrieve.

javascript
  1. 1

    Hash-based lookup depends on the key's hash value.

  2. 2

    Changing equality-relevant state can change the bucket mapping.

  3. 3

    The entry may remain physically stored in its old bucket.

  4. 4

    Removal using the mutated key may also fail.

  5. 5

    Immutable keys are safer and easier to reason about.

  6. 6

    If mutation is unavoidable, fields participating in equality and hashing should not change while the key is in the map.

Follow-up Questions

  • Why are strings commonly good HashMap keys?
  • What happens if only a non-hash field is mutated?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.