Middle
What is the purpose of the IdentityHashMap class in Java?
sobes.tech AI
Answer from AI
IdentityHashMap is used when key comparison should be based on reference (==) rather than value (equals()) or hash code. This is useful in the following scenarios:
- Implementing graph or tree traversal to avoid cycles, where it is important to track visited nodes by their identity.
- Serializing objects where it is necessary to preserve the structure of the object graph considering their identity.
- Cloning objects while maintaining references to shared sub-objects.
- Testing, when it is necessary to check the equality of instances rather than their content.
Main difference from the standard HashMap:
| Feature | HashMap |
IdentityHashMap |
|---|---|---|
| Key comparison | Uses equals() and hashCode() |
Uses == operator |
| Hashing | Based on hashCode() |
Based on the "system" hash of the object |
Example:
// Example of using IdentityHashMap
IdentityHashMap<Object, String> map = new IdentityHashMap<>();
Object key1 = new Object();
Object key2 = new Object();
Object key3 = key1; // key3 references the same object as key1
map.put(key1, "Value for key1");
map.put(key2, "Value for key2");
map.put(key3, "Value for key3"); // Overwrites the value for key1, since key3 == key1
System.out.println(map.size()); // Output: 2 (key1/key3 and key2 are considered different keys)
System.out.println(map.get(key1)); // Output: Value for key3 (the last value for this reference)
System.out.println(map.get(key2)); // Output: Value for key2
// Example of using HashMap for comparison
HashMap<Object, String> regularMap = new HashMap<>();
Object key1_reg = new Object();
Object key2_reg = new Object();
Object key3_reg = key1_reg;
regularMap.put(key1_reg, "Value for key1_reg");
regularMap.put(key2_reg, "Value for key2_reg");
regularMap.put(key3_reg, "Value for key3_reg"); // Also overwrites, but only if equals() and hashCode() are the same (by default for Object, true when `==`)
System.out.println(regularMap.size()); // Output: 2 (if `equals()` and `hashCode()` are not overridden)