Quick revision
The short answer
IdentityHashMap is a Map that treats two keys as the same only if they are the same object, comparing with == and hashing with System.identityHashCode instead of equals and hashCode. It deliberately breaks the general Map contract, and internally it uses one flat array with keys and values side by side and linear probing instead of linked nodes. It is the right choice when object identity is what we care about, such as tracking visited objects in a graph traversal, deep copy or serialization, and the wrong choice for value-like keys such as Strings or boxed numbers.
What to remember
In this answer, we saw that IdentityHashMap compares keys with == and hashes them with System.identityHashCode, deliberately violating the Map contract. It stores keys and values side by side in one array and resolves collisions with linear probing, which saves memory and avoids node objects. It is the right choice for identity-based algorithms such as graph traversal, deep copy and serialization, where Collections.newSetFromMap gives an identity set, and the wrong choice for value keys like Strings and boxed numbers.
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.
IdentityHashMap is a Map that treats two keys as the same only if they are the same object, comparing with == and hashing with System.identityHashCode instead of equals and hashCode. It deliberately breaks the general Map contract, and internally it uses one flat array with keys and values side by side and linear probing instead of linked nodes. It is the right choice when object identity is what we care about, such as tracking visited objects in a graph traversal, deep copy or serialization, and the wrong choice for value-like keys such as Strings or boxed numbers.
Why this question is asked
Most of the time we want maps to treat equal values as the same key, and HashMap does that. But some algorithms work on objects themselves, not on their values: they need to know whether they have already seen this particular object. Using HashMap there gives subtle wrong answers. Interviewers ask about IdentityHashMap to see whether we understand the difference between equality and identity and know which tool the JDK provides for each. In this answer, we will recap equality versus identity, see how IdentityHashMap is built, look at where it is the correct tool, and then see what goes wrong when we use it with value keys.
1A Quick Recap of Equality Versus Identity
Two objects are identical when they are the same object in memory, which is what the == operator checks for references. Two objects are equal when their equals method says so, which for most value classes means they hold the same data. Two separate String objects containing "abc" are equal but not identical.
The Map interface specifies that keys are compared with equals. HashMap follows that rule by calling hashCode to find a bucket and equals to find the key. IdentityHashMap's Javadoc says plainly that it violates this general contract on purpose: it compares keys with == and uses System.identityHashCode, a hash based on the object itself that ignores any hashCode override.
2How IdentityHashMap Is Implemented
HashMap stores a table of buckets, and each bucket holds a chain of Node objects, or a tree for crowded buckets. IdentityHashMap does not create any node objects. It keeps a single Object[] array in which each key is stored at an even index and its value at the next odd index.
To insert, it computes an index from System.identityHashCode(key), and if that slot is taken by a different key, it moves forward two positions at a time to the next slot, wrapping around at the end, until it finds the key or an empty slot. This technique is called linear probing, a form of open addressing where collisions are resolved by searching nearby slots in the same array rather than by chaining. The table is kept at most about two thirds full so that probe runs stay short, and it doubles when it passes that threshold.
The flat layout has two benefits. There is no per-entry object, so memory use is lower than HashMap, and a lookup walks consecutive array slots, which is friendly to the CPU cache. Comparing with == is also a single instruction, cheaper than calling equals.
| Index | Contents | Meaning |
|---|---|---|
| 0 | key: orderA | entry 1 key |
| 1 | value: copyA | entry 1 value |
| 2 | null | empty slot |
| 3 | null | empty slot |
| 4 | key: orderB | entry 2 key (probed past a collision) |
| 5 | value: copyB | entry 2 value |
3Where It Is the Right Tool
The classic uses are algorithms that walk an object graph. A graph traversal that must not visit the same object twice needs a visited set based on identity, because two different nodes may be equal by value and still need separate visits. A deep copy needs a map from each original object to its copy, so that shared references and cycles are preserved. Serialization frameworks need to know whether an object has already been written so they can write a back-reference instead of a second copy. Proxy and instrumentation tools use it to track objects they have wrapped.
There is no IdentityHashSet in the JDK, but Collections.newSetFromMap turns any map into a set with the same key semantics.
Notice that the walk also stays safe if Node has a buggy or expensive equals or hashCode, because IdentityHashMap never calls them. In graph code that is a real advantage: calling hashCode on a node whose hashCode includes its children can recurse into a cycle.
4Why It Is Wrong for Value Keys
Value-based keys such as Strings, boxed Integers and Longs, BigDecimals and records are meant to be compared by value. Code that looks them up usually creates a new object with the same value, and with IdentityHashMap that lookup misses. The behaviour can even look correct in a test, because the JVM reuses some objects: string literals are interned, and Integer.valueOf caches values from -128 to 127.
So a test with small numbers passes and production with real ids fails. The rule is to use IdentityHashMap only when the algorithm is genuinely about which object it is, and to document that choice in a comment, because readers will expect Map semantics.
5Follow-up questions
Is IdentityHashMap thread-safe?
No. Like HashMap, it has no internal synchronization. If several threads share one, we must wrap it with Collections.synchronizedMap or guard it with our own lock. In practice, it is usually a local variable inside one traversal or one copy operation, which avoids the question.
Can System.identityHashCode values collide?
Yes. It is an int derived from the object, and distinct objects can share the same value. IdentityHashMap handles that like any collision, by probing to the next slot and comparing with ==, so correctness does not depend on the hash being unique.
What is the expected maximum size constructor argument for?
new IdentityHashMap<>(expectedMaxSize) sizes the internal array so that the map can hold that many entries without resizing. It is useful when we know roughly how many objects a traversal will touch, because each resize rehashes every entry into a new array.
6Conclusion
In this answer, we saw that IdentityHashMap compares keys with == and hashes them with System.identityHashCode, deliberately violating the Map contract. It stores keys and values side by side in one array and resolves collisions with linear probing, which saves memory and avoids node objects. It is the right choice for identity-based algorithms such as graph traversal, deep copy and serialization, where Collections.newSetFromMap gives an identity set, and the wrong choice for value keys like Strings and boxed numbers.
Open with
IdentityHashMap is a Map that compares keys by reference, using == and System.identityHashCode instead of equals and hashCode. The Javadoc says it intentionally violates the general Map contract, so two different String objects with the same text are two different keys.
Then, if they want more
Internally it does not use nodes and buckets like HashMap. It has one Object array with each key at an even index and its value right after it, and collisions are handled with linear probing, moving to the next pair of slots until it finds the key or an empty slot. That makes it compact and cache friendly.
It is the correct choice when the algorithm is about object identity: tracking visited objects in a graph traversal, mapping originals to copies in a deep copy, or knowing which objects a serializer has already written. In those cases two distinct objects that happen to be equal must stay separate, and not calling hashCode also avoids recursion through cycles.
For a visited set I would use Collections.newSetFromMap with a new IdentityHashMap. It is wrong for value-based keys like Strings, Integers or records, because a lookup with an equal but different object misses, and the Integer cache can hide that bug in tests with small numbers.
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 "What is IdentityHashMap, how is it implemented, and when is it the correct choice?": https://scrivio-interview-library.netlify.app/java/hashmap-internals/5455364ec9/