Sub topic 11
Mutable keys: when objects get lost in a HashMap
This chapter assumes you know Java classes, fields, constructors, method overriding, and basic Map operations. You should also know that hashCode() returns an integer used by hash-based collections.
A HashMap stores each entry by the key's hash code. It uses the hash code to choose a bucket, then uses equals() to find the exact key inside that bucket. This makes lookup fast, but it creates an important rule:
> A key must not change in any way that affects equals() or hashCode() while it is stored in a HashMap.
How mutation loses an entry
Consider a list used as a key:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MutableKeyDemo {
public static void main(String[] args) {
List<Integer> key = new ArrayList<>(List.of(1));
Map<List<Integer>, String> map = new HashMap<>();
map.put(key, "value");
key.add(2); // Changes the list's equals and hashCode results
System.out.println(map.get(key)); // null
System.out.println(map.containsKey(key)); // false
System.out.println(map.containsValue("value")); // true
}
}The entry has not been deleted. It is still inside the map, which is why containsValue("value") prints true. However, the key now has a different hash code from the one it had when put stored the entry.
The lookup calculates the new hash code and searches the new bucket. The entry remains in the old bucket, so the lookup cannot find it.
What counts as dangerous mutation?
A field is dangerous when it participates in equality or hash calculation. For example, if a Person key uses id and email in equals() and hashCode(), changing either field can make the key unreachable.
| Key design | Safe while stored? | Reason |
|---|---|---|
| `String` | Yes | `String` is immutable |
| Java record with immutable components | Usually | Its components cannot be reassigned |
| `ArrayList` | No | Its contents and hash code can change |
| Mutable class with changing fields | No | Equality can change after insertion |
A reference declared final does not make the referenced object immutable:
final List<String> names = new ArrayList<>();
names.add("Ada"); // The reference cannot change, but the list canSafer designs
Prefer an immutable key. A value class should make its equality fields private and final, avoid setters, and defensively copy mutable inputs.
import java.util.Objects;
public final class UserKey {
private final int id;
public UserKey(int id) {
this.id = id;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof UserKey)) return false;
UserKey that = (UserKey) other;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}If a key must change, remove the entry before changing it, then insert it again. In practice, replacing the key with a new immutable object is often clearer. Do not assume that calling remove with the mutated key will work, because lookup may already be broken.
> callout note > Hash-based collections trust keys to remain stable. The map does not monitor keys and cannot move an entry when a key changes.
Exercise
Exercise
Why can map.containsValue("value") be true while map.containsKey(key) is false after key is mutated?
Show answer
The entry still exists in its original bucket, so the value can be found by scanning entries. The mutated key now produces a different hash code, so key lookup searches the wrong bucket.