A HashMap key must keep the equality and hash behavior used at insertion for as long as the mapping remains stored.
Java HashMap mutable keys: freeze identity before insertion
Separate lookup identity from editable state
An order route may change, but the route ID used to find that order should not. Mutating an object after it becomes a map key can change equals or hashCode; the Map contract leaves the resulting lookup behavior unspecified. Do not build recovery logic around a particular failed or successful get call after such a mutation.
The working program uses an immutable String route ID as its key. It stores mutable status as the value and replaces that value when the route moves. This keeps lookup identity stable while allowing the operational state to change. Equality and hashing must follow the same stable key fields.
Prefer a copied composite key
When one field cannot identify a record, construct an immutable key from the required parts and reject null or invalid parts at construction. In Java 17+, a record is concise, but a record containing a mutable array still needs a defensive copy. Array ownership in records shows why final fields alone do not freeze their contents.
A mutable key used in a TreeMap has a related problem: a comparator-visible edit can invalidate the tree's ordering. The failure boundary is the key contract, not the brand of map.
Working program
import java.util.HashMap;
import java.util.Map;
public class RouteStatusIndex {
public static void main(String[] args) {
Map<String, String> statusByRouteId = new HashMap<>();
String stableRouteId = "north-47";
statusByRouteId.put(stableRouteId, "queued");
statusByRouteId.replace(stableRouteId, "departed");
System.out.println(statusByRouteId.get(stableRouteId));
System.out.println(statusByRouteId.containsKey("north-48"));
}
}Output
departed
falseCost and ownership
HashMap lookup is expected O(1) with a sound key distribution, but a collision-heavy or hostile key set can increase work. The map retains O(n) entries. Stable keys protect correctness; they do not make updates across several maps transactional.
Common Mistakes
- Do not edit a key field that participates in equals or hashCode after insertion.
- Do not treat an unmodifiable wrapper around a caller-owned mutable object as an immutable key.
- Do not confuse changing a map value with changing its key.
Read next
Java HashMap: keys, collisions, and update operations, Java equals and hashCode: stable value keys, Java records with arrays: copy on input and output, Java TreeMap: ordered keys and range views.
