IdentityHashMap compares keys by reference identity, so equal values held by distinct objects remain separate keys.
Java IdentityHashMap: reference identity is not value equality
The same text can represent two keys
Two newly allocated receipt IDs both contain R-41. HashMap treats them as one key by String.equals; IdentityHashMap keeps two entries because the String objects are not the same reference. The displayed sizes make that distinction visible without relying on map iteration order.
This map is appropriate for an object graph that needs to track exact instances, not for deduplicating business identifiers. HashMap and equality contracts cover value-key behavior.
Identity is an ownership decision
Interned strings, reused boxed values or pooled objects can make apparent identity tests change with construction details. Never use IdentityHashMap to compare user IDs, receipt codes or database keys. The key's displayed text is not its identity.
Working program
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
public class ReceiptInstanceIndex {
public static void main(String[] args) {
String first = new String("R-41");
String second = new String("R-41");
Map<String, Integer> byValue = new HashMap<>();
Map<String, Integer> byInstance = new IdentityHashMap<>();
byValue.put(first, 1); byValue.put(second, 2);
byInstance.put(first, 1); byInstance.put(second, 2);
System.out.println("equal=" + first.equals(second) + ", same=" + (first == second));
System.out.println("value keys=" + byValue.size() + ", instance keys=" + byInstance.size());
}
}Output
equal=true, same=false
value keys=1, instance keys=2Costs and boundaries
Both maps require space for their retained entries. This fixture checks equality semantics, not comparative throughput or memory measurements. Identity keys still keep their referents reachable while the map retains them.
Common Mistakes
- Do not index business identifiers by object identity.
- Do not infer identity from equal text or from an object's toString result.
- Do not mistake IdentityHashMap for a weak-reference map.
Read next
Java HashMap: keys, collisions, and update operations, Java equals and hashCode: stable value keys, Java weak references: reachability is not a cache eviction schedule.
