Video in progress
When do you need an IdentityHashMap?
When keys must be compared by ==, not equals: walking an object graph and checking "have I seen this exact object?", serialization, deep copy, proxies. It uses System.identityHashCode and open addressing (linear probing).
📖 Answer
Example: detecting cycles when deep-copying an object graph or writing it to JSON.
Map<Object, Object> copies = new IdentityHashMap<>();
Object deepCopy(Object src) {
Object done = copies.get(src);
if (done != null) return done; // this object has already been copied
Object copy = shallowClone(src);
copies.put(src, copy);
// ... copy the fields recursively
return copy;
}
If you used a HashMap here, two different objects that happen to be equal by equals would be treated as one, and the copy would come out wrong. Another risk: some classes' hashCode walks their fields recursively and throws a StackOverflowError on a cyclic graph. identityHashCode doesn't do that.
The internal structure is different too: there are no separate Node objects, and the key and value sit next to each other in one array. In some cases this saves memory.
Important: IdentityHashMap deliberately violates the Map contract (which requires equals). Don't use it instead of HashMap in ordinary business code, and be careful when you pass it to other code as a Map. It is not for multiple threads either.
Sign up to mark studied questions and save your progress.