Sub topic 11
Mutable keys: when objects get lost in a HashMap
This chapter assumes you know how HashMap and HashSet use hashCode and equals, and that you can write both methods for a value class. It covers one failure that follows from those rules. If an object's hash code changes while it sits in a hash-based collection, the collection can no longer find it, and it reports no error.
What the map remembers
A HashMap does its work at insertion time. When you call put(key, value), the map does the following:
- It calls
key.hashCode()once. - It mixes the bits of that value and uses the result to choose a bucket in its internal array.
- It stores a node in that bucket. The node holds the key reference, the value, and a copy of the hash it computed.
On a later get(k), the map computes k.hashCode() again and goes to the matching bucket. It then walks the nodes in that bucket. For each node it compares the stored hash with the new hash, and only then calls equals.
The map never recomputes the hash of a key already stored. It trusts that the hash it saw at put time is still correct. If the key's hash code depends on state that later changes, the stored position and the current hash disagree. The map has no way to detect this.
The lost entry in action
The next program stores a List<Integer> as a key and then mutates that list. List.hashCode is computed from the elements, so adding an element changes it.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LostKey {
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");
System.out.println("hash at put: " + key.hashCode()); // 32
key.add(2); // mutates the key after it was stored
System.out.println("hash now: " + key.hashCode()); // 994
System.out.println(map.get(key)); // null
System.out.println(map.get(List.of(1))); // null
System.out.println(map.get(List.of(1, 2))); // null
System.out.println(map.containsKey(key)); // false
System.out.println(map.containsValue("value")); // true
System.out.println(map.size()); // 1
System.out.println(map.remove(key)); // null
System.out.println(map); // {[1, 2]=value}
}
}The entry is still in the map. size() counts it, containsValue finds it, and printing the map shows it. Every lookup by key fails, though, for two different reasons:
map.get(key)andmap.get(List.of(1, 2))compute the hash 994. With the default 16 buckets, 994 maps to bucket 2, which is empty. The map never visits the bucket that holds the node.map.get(List.of(1))computes the old hash 32 and does reach bucket 0, where the node is stored. The stored hash matches, so the map callsequals. The stored key is now[1, 2], which is not equal to[1], so the lookup fails.
No argument can find this entry. A key that equals the stored key has a different hash. A key with the original hash is not equal to the stored key.
Consequences beyond a failed lookup
A lost entry is worse than a missing one, because it keeps existing without being reachable.
- Memory leak.
remove(key)fails, so nothing in normal code can delete the entry. It stays until the whole map is discarded orclear()is called. - Duplicate keys. You can
putan equal key again. The map treats it as new and stores a second entry, so a map can hold two keys that areequalsto each other. - Inconsistent views.
size(), iteration, andcontainsValuesee the entry.get,containsKey, andremovedo not. - Resizing can hide or reveal the problem. When the map grows, it redistributes nodes using their stored hashes, not the current ones. The entry stays unreachable after a resize. Because the symptom depends on bucket count and on how far the hash moved, a test with a few entries can pass while production data fails.
HashSet is a HashMap underneath, so the same thing happens there. A mutated element makes contains return false and remove do nothing, and the element still shows up when you iterate.
A mutable object does not have to be a collection to cause this. This class has the same flaw:
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class MutableUser {
private String name;
public MutableUser(String name) { this.name = name; }
public void setName(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MutableUser)) return false;
return Objects.equals(name, ((MutableUser) o).name);
}
@Override
public int hashCode() { return Objects.hashCode(name); }
public static void main(String[] args) {
Set<MutableUser> users = new HashSet<>();
MutableUser u = new MutableUser("ana");
users.add(u);
u.setName("ben");
System.out.println(users.contains(u)); // false
System.out.println(users.size()); // 1
}
}Here the equals and hashCode are consistent with each other. The bug comes from combining them with mutable state in a collection that assumes the hash is stable.
Rules that prevent it
The contract in the Object documentation says hashCode must return the same value across calls only if the fields used in equals are unchanged. It does not promise that the fields stay unchanged. The responsibility for stability falls on you, and there are four ways to meet it.
Make the key immutable
An immutable class has final fields that never change after construction, so its hash can never move. This is the best option, and it is why String, Integer, and LocalDate work well as keys. Records give you the same effect, provided their components are themselves immutable.
Copy mutable inputs
A class with final fields can still be unstable if a field refers to a mutable object. Copy on the way in and, if you expose the field, on the way out:
import java.util.List;
import java.util.Objects;
public final class Route {
private final List<String> stops;
public Route(List<String> stops) {
this.stops = List.copyOf(stops); // unmodifiable snapshot
}
public List<String> stops() { return stops; }
@Override
public boolean equals(Object o) {
return this == o || (o instanceof Route r && stops.equals(r.stops));
}
@Override
public int hashCode() { return stops.hashCode(); }
}List.copyOf returns an unmodifiable list and throws a NullPointerException if the input contains null. If the caller later changes the list they passed in, the Route is unaffected. This example uses pattern matching for instanceof, which needs Java 16 or later.
Hash only stable fields
If an entity has an immutable identity such as an id, base equals and hashCode on that field alone. Other fields can then change freely:
import java.util.Objects;
public class Account {
private final long id;
private String owner; // may change; not part of equality
public Account(long id, String owner) {
this.id = id;
this.owner = owner;
}
public void setOwner(String owner) { this.owner = owner; }
@Override
public boolean equals(Object o) {
return this == o || (o instanceof Account a && id == a.id);
}
@Override
public int hashCode() { return Long.hashCode(id); }
}This changes what equality means: two accounts with the same id and different owners are equal. That is correct only if the id really identifies the entity. Objects that have not been saved yet and have no id need separate care.
Remove, change, re-add
When you must mutate an object that is already a key, take it out of the collection first and put it back afterwards:
users.remove(u); // hash is still the old one, so this succeeds
u.setName("ben");
users.add(u); // stored under the new hashThis works, but it depends on every caller following the same discipline, so it is the weakest of the four.
| Approach | Strength | Cost |
|---|---|---|
| Immutable key | Hash can never change | Updates create new objects |
| Defensive copy | Protects against outside mutation | Copy time and memory |
| Hash an immutable id | Other fields stay mutable | Equality is by identity of the entity only |
| Remove, mutate, re-add | No class change | Easy to forget, not thread-safe |
Other collections with the same trap
TreeMap and TreeSet order their keys with compareTo or a Comparator. If you mutate a field that takes part in the ordering, the tree's structure no longer matches the ordering, and lookups can fail in the same way. ConcurrentHashMap and LinkedHashMap also rely on a stable hash. Making the collection thread-safe does not make a mutable key safe.
Spotting the problem in practice
When a key lookup fails for a value you are sure you stored, work through these checks:
- Print
key.hashCode()at the moment you insert it and again at the moment you look it up. If they differ, the key was mutated. - Check whether
containsValuefinds the entry. If it does, andcontainsKeydoes not, the key's hash has moved. - Look for fields used in
hashCodethat have setters, or that refer to collections or other mutable objects. - Check whether the key came from a shared object that another part of the program may have changed.
Exercise
You store a StringBuilder as a key in a HashMap, and later append text to it. Will map.get(sameBuilder) find the entry? Explain, and say what changes if you use sb.toString() as the key.
Show answer
It will find the entry. StringBuilder does not override hashCode or equals, so it uses the identity-based versions from Object. The hash depends on the object reference, not on the characters, so appending text does not change it. This is safe only because equality is by identity, so no other StringBuilder with the same text can match. Using sb.toString() gives a String, which is immutable and compares by content. The key is then stable, and any String with the same characters finds the entry. The stored key is a snapshot, so later appends to the builder do not affect it.
Exercise
In the MutableUser example, users.remove(u) is called after u.setName("ben"). Does the removal succeed, and what is users.size() afterwards?
Show answer
The removal fails and returns false, because the set computes the new hash for "ben" and looks in a bucket that does not contain the node. (Even if it reached the right bucket, the stored hash would not match.) users.size() stays 1, and the object remains in the set, reachable only by iteration. To remove it you must call users.remove(u) before setName, or call users.clear().