Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

You are writing a deepCopy(Object root) utility for an object graph that may contain cycles and shared references. Describe how you would use IdentityHashMap and why HashMap would be wrong.

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.

Java
final class Node {
String name;
List<Node> links = new ArrayList<>();
Node(String name) { this.name = name; }
}
Node naiveCopy(Node n) {
Node c = new Node(n.name);
for (Node link : n.links) c.links.add(naiveCopy(link));
return c;
}
Node a = new Node("a"), b = new Node("b");
a.links.add(b);
b.links.add(a); // cycle a -> b -> a
naiveCopy(a); // StackOverflowError: a, b, a, b, ...

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.

Java
Node deepCopy(Node root) {
return copy(root, new IdentityHashMap<>());
}
private Node copy(Node n, Map<Node, Node> copies) {
if (n == null) return null;
Node existing = copies.get(n);
if (existing != null) return existing; // already copied: reuse, keeps sharing
Node c = new Node(n.name);
copies.put(n, c); // register BEFORE copying the links
for (Node link : n.links) c.links.add(copy(link, copies));
return c;
}
Node ca = deepCopy(a);
ca != a; // true: a new object
ca.links.get(0).links.get(0) == ca; // true: the cycle points to the copy
Step throughCopying the cycle a -> b -> a
copy()IdentityHashMap
get(a): null, create ca
put(a, ca)
copy link b
get(b): null, create cb, put(b, cb)
copy b's link a
get(a)
ca: reuse, recursion stops

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.

HashMap versus IdentityHashMap for the copies map
SituationHashMapIdentityHashMap
Two distinct nodes, equal by namemerged into one copytwo copies, shape kept
Shared reference reached twiceone copy (if equals is sane)one copy
hashCode includes links, graph has a cycleStackOverflowError while hashingnever calls hashCode
Key mutated during copymay land in wrong bucketidentity 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.

Java
Node deepCopyIterative(Node root) {
if (root == null) return null;
Map<Node, Node> copies = new IdentityHashMap<>();
Deque<Node> work = new ArrayDeque<>();
copies.put(root, new Node(root.name));
work.push(root);
while (!work.isEmpty()) {
Node original = work.pop();
Node c = copies.get(original);
for (Node link : original.links) {
Node linkCopy = copies.get(link);
if (linkCopy == null) {
linkCopy = new Node(link.name);
copies.put(link, linkCopy); // registered on discovery, so cycles stop
work.push(link);
}
c.links.add(linkCopy);
}
}
return copies.get(root);
}
// A chain of 1,000,000 nodes copies fine; the recursive version overflows the stack.

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.

What to say in the interviewAbout 80 seconds aloud

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.
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/