What happens if you mutate an object after using it as a HashMap key?
⚡ Short Answer
The key's hashCode changes, so it now maps to a different bucket than where it was stored. get() looks in the new bucket and can't find it — the entry becomes a 'ghost': present but unretrievable, and it leaks memory.
☕Coffee Chat Question
Concept Made Simple
“What happens if you mutate an object after using it as a HashMap key?”
🧠Mind Map Answer
Remember It Faster
HashMap places a key by its hashCode at insert time. Mutate a field used in hashCode/equals and the key effectively moves — but the entry stays in the old bucket, now unreachable by lookup.
⌨️Hands-on Keyboard
Learn by Doing
Map<Point,String> m = new HashMap<>();
Point p = new Point(1,1);
m.put(p, "A");
p.setX(99); // mutated key!
System.out.println(m.get(p)); // null — wrong bucketnull
🔥What If?
Think Beyond the Expected
How does this cause a slow memory leak?
The 'ghost' entry can never be found or removed via the key, so it stays in the map forever. In a long-lived cache keyed by mutable objects, these orphaned entries accumulate and grow the heap.
😂Real World
Using mutable JPA entities or DTOs as map/set keys leads to entries 'disappearing' after a field update and to subtle leaks — the reason value objects/keys should be immutable.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Using mutable objects as map/set keys
- ✗Including mutable fields in hashCode
- ✗Mutating keys held in a cache
✅Best Practices
- ✓Use immutable keys (String, records, value objects)
- ✓Base hashCode on immutable fields only
- ✓Never mutate an object while it's a key
🔁Follow-up Questions
- 1Why are String and Integer good keys?
- 2How does this relate to JPA entity equals/hashCode?
- 3What fields should hashCode use?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: HashMap Internals (Java Collections) Interview question: "What happens if you mutate an object after using it as a HashMap key?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.