17 / 17

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

Mutable HashMap Keys

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.

Difficulty: 4/10

Follow-up Questions

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