Let’s get into the difference between HashMap
and IdentityHashMap
, and when to use this strange beast of a map.
🎯 TL;DR:
✅
HashMap
compares keys using.equals()
✅IdentityHashMap
compares keys using==
(object reference equality)
That’s the core difference — but it leads to some very different behaviors.
🧪 HashMap
: Normal, Everyday Map
- Uses
.equals()
and.hashCode()
to compare keys. - Two different objects with the same content are treated as the same key.
Map<String, String> map = new HashMap<>();
map.put(new String("key"), "value1");
map.put(new String("key"), "value2");
System.out.println(map.size()); // 1 — keys are equal by content
🧪 IdentityHashMap
: Compares by ==
- Uses reference equality — two keys are equal only if they are the same object.
- Ignores
.equals()
and.hashCode()
.
Map<String, String> map = new IdentityHashMap<>();
map.put(new String("key"), "value1");
map.put(new String("key"), "value2");
System.out.println(map.size()); // 2 — keys are different objects!
🔍 Use Cases for IdentityHashMap
You don’t use IdentityHashMap
in everyday apps. It’s used in very specific cases, like:
✅ 1. Object identity tracking
- You want to associate data with exact object instances, not logically equal objects.
- Useful in graph algorithms or serialization frameworks.
✅ 2. Performance optimization
- Avoids calling
equals()
andhashCode()
, which might be expensive for large objects. - But only when you care about references, not content.
✅ 3. Java internals
- Used internally by the JVM, e.g., in
ClassLoader
s or tracking references during garbage collection, etc.
⚠️ Gotchas
IdentityHashMap
violates Map contract in some cases (e.g., it doesn’t behave like aSet
of keys in the usual way).- Iteration order is also not guaranteed or predictable.
- Dangerous to use unless you really know what you’re doing.
🧠 Summary Table
Feature | HashMap | IdentityHashMap |
---|---|---|
Key equality | .equals() | == (reference equality) |
Hashing | .hashCode() | System.identityHashCode() |
Allows duplicates | ❌ No (based on content) | ✅ Yes (if different instances) |
Use cases | General-purpose | Object tracking, performance |
Null keys | ✅ 1 allowed | ✅ Multiple allowed |