IdentityHashMap uses reference identity for both keys and values, so two equal-but-distinct String objects occupy separate entries where a normal HashMap would merge them into one.
Map<String, Integer> identity = new IdentityHashMap<>();
String a = new String("key");
String b = new String("key");
identity.put(a, 1);
identity.put(b, 2);
System.out.println("IdentityHashMap size: " + identity.size());
System.out.println("a.equals(b): " + a.equals(b));
Map<String, Integer> normal = new HashMap<>();
normal.put(a, 1);
normal.put(b, 2);
System.out.println("HashMap size: " + normal.size());
IdentityHashMap size: 2
a.equals(b): true
HashMap size: 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27