Quick revision
The short answer
We keep an IdentityHashMap<Object, Object> from each original object to its copy. Before copying an object we look it up, and if a copy already exists we reuse it, which preserves shared references. We put the new copy into the map before copying its fields, so a cycle that leads back to the object finds the copy and stops. HashMap would be wrong because it compares with equals and hashCode, merging distinct but equal objects into one copy and possibly recursing through cycles inside hashCode itself.
What to remember
In this answer, we saw that a deep copy must preserve shared references and survive cycles, and both depend on object identity. An IdentityHashMap from original to copy, checked before each copy and filled before copying fields, gives one copy per original and stops cycles. HashMap would merge distinct but equal objects and could recurse into cycles or throw inside hashCode. For very deep graphs, an explicit stack replaces recursion and avoids StackOverflowError.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We keep an IdentityHashMap<Object, Object> from each original object to its copy. Before copying an object we look it up, and if a copy already exists we reuse it, which preserves shared references. We put the new copy into the map before copying its fields, so a cycle that leads back to the object finds the copy and stops. HashMap would be wrong because it compares with equals and hashCode, merging distinct but equal objects into one copy and possibly recursing through cycles inside hashCode itself.
Why this question is asked
Deep copies come up when we snapshot state for undo, clone a document before editing it, or isolate test fixtures. Real object graphs are rarely trees: two orders can point to the same customer, and a parent can point to its children while each child points back to its parent. A naive recursive copy duplicates the shared customer and loops forever on the parent and child. Interviewers ask this question because it checks whether we understand object identity, cycles and recursion depth together. In this answer, we will recap the two problems a deep copy must solve, write the copy with IdentityHashMap, see why the order of operations matters, show why HashMap breaks it, and finish with an iterative version for very deep graphs.
1What a Deep Copy Must Preserve
A shallow copy creates a new top-level object but shares everything it points to. A deep copy creates new objects for the whole reachable graph, so changing the copy never affects the original.
Two properties make it hard. The first is shared references: if order1 and order2 both point to the same Customer object, the copy should have copyOfOrder1 and copyOfOrder2 pointing to one shared copy of the customer, not two separate customers. The second is cycles: if a Department points to its Employees and each Employee points back to its Department, following references never ends unless we remember where we have been. Both properties are about which object we are looking at, not about what it contains, so we need a map keyed by identity.
2The Broken Version First
Here is a small graph type and a copy that ignores both problems.
Notice that even without the cycle, a node reachable along two paths would be copied twice, so the copy would have a different shape from the original.
3Writing the Copy With IdentityHashMap
The fix is a map from original to copy, consulted before every copy. The essential detail is where we insert into it.
7 messages in order. Play them, or step through them one at a time.
Registering ca before copying the links is what ends the cycle.
The reason we register the copy before copying the links is the cycle. When we copy a, we put a -> ca in the map, then copy b. b links to a, so copy(a) runs again, finds ca in the map, and returns it. Without the early put, the second visit to a would not find anything and we would be back in the infinite recursion. If we registered only at the end, sharing would still work for trees, but cycles would not.
4Why HashMap Would Be Wrong
Suppose Node overrides equals and hashCode to compare by name, which is a natural thing to do for a value-like class. With a HashMap of copies, two distinct nodes both named "x" would be equal, so the second one would find the first one's copy and reuse it. The copy would merge two separate objects into one, silently changing the graph's shape.
There is a second, nastier failure. If hashCode includes the links, which a generated implementation over all fields would do, then hashing a node hashes its links, which hash their links, and in a cycle that recursion never ends. Even mid-copy, a partly filled copy may throw from hashCode because a field is still null. IdentityHashMap never calls equals or hashCode on the keys. It uses == and System.identityHashCode, so it treats every object as distinct, which is exactly the meaning of a deep copy, and it is safe on objects whose hashCode is broken or recursive.
| Situation | HashMap | IdentityHashMap |
|---|---|---|
| Two distinct nodes, equal by name | merged into one copy | two copies, shape kept |
| Shared reference reached twice | one copy (if equals is sane) | one copy |
hashCode includes links, graph has a cycle | StackOverflowError while hashing | never calls hashCode |
| Key mutated during copy | may land in wrong bucket | identity never changes |
5Handling Very Deep Graphs Without Recursion
Recursion uses one stack frame per level. A linked list of 100,000 nodes copied recursively will throw StackOverflowError on a default thread stack. For such graphs, we replace the call stack with an explicit work queue. We create each copy as soon as we discover its original, and fill in its links when we pop it.
The same rule holds: an object goes into the map the moment we create its copy, before its links are processed. The heap-allocated ArrayDeque can grow as large as needed, so depth is limited only by memory.
6Follow-up questions
How would you make this work for arbitrary classes, not just Node?
We would need a way to create an empty instance and copy each field, typically through reflection or a code-generated copier, and the same IdentityHashMap would track every object across all types. Immutable values such as Strings, boxed numbers and records of immutable fields can be shared rather than copied. In practice, libraries or serialization round trips are often used, but they rely on the same identity tracking inside.
Is serialization a good way to deep copy?
Java serialization handles cycles and sharing, because its stream keeps an identity table of written objects. But it is slow, requires Serializable on every class, and carries security risks when used on untrusted data. For hot paths or large graphs, an explicit copy or a copy constructor per class is faster and clearer.
7Conclusion
In this answer, we saw that a deep copy must preserve shared references and survive cycles, and both depend on object identity. An IdentityHashMap from original to copy, checked before each copy and filled before copying fields, gives one copy per original and stops cycles. HashMap would merge distinct but equal objects and could recurse into cycles or throw inside hashCode. For very deep graphs, an explicit stack replaces recursion and avoids StackOverflowError.
Open with
I would keep an IdentityHashMap from each original object to its copy. When I copy an object, I first look it up; if it is already there, I return the existing copy, which keeps shared references shared, so two orders that point to one customer still point to one copied customer.
Then, if they want more
If it is not there, I create the new object and put it in the map before copying its fields. That order is what makes cycles work: when the traversal comes back to the same object through a back-reference, it finds the copy and stops instead of recursing forever. HashMap would be wrong for two reasons.
It compares with equals and hashCode, so two distinct objects that happen to be equal would be merged into a single copy and the graph's shape would change. And calling hashCode on objects in a cyclic graph can recurse through the cycle, or throw on a half-built copy.
IdentityHashMap uses reference equality and identityHashCode, so it never calls those methods and treats every object as distinct, which is what a deep copy means. For very deep graphs, like long linked chains, I would replace recursion with an explicit ArrayDeque as the work stack, registering each copy when I discover it, to avoid StackOverflowError.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You are writing a deepCopy(Object root) utility for an object graph that may contain...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/21fd52b1d2/