Middle+
What is the difference between HashMap and IdentityHashMap?
sobes.tech AI
Answer from AI
The main difference lies in how they compare keys.
- HashMap uses the
equals()method and the hash code of the key to determine equality, which corresponds to the standard semantics of object equality. - IdentityHashMap compares keys strictly by reference (using
==), ignoring theequals()method. This means that two different objects, even if they are "equal" according to theirequals()method, will be considered different keys inIdentityHashMapif they have different memory addresses.
Example:
// HashMap
Object key1 = new String(" key");
Object key2 = new String(" key");
Map<Object, String> hashMap = new HashMap<>();
hashMap.put(key1, "value 1");
hashMap.put(key2, "value 2"); // overwrites the value for " key"
// IdentityHashMap
Map<Object, String> identityHashMap = new IdentityHashMap<>();
identityHashMap.put(key1, "value 1");
identityHashMap.put(key2, "value 2"); // adds a second entry, since key1 != key2 by reference
IdentityHashMap is used less frequently, for example:
- During serialization/deserialization, when object identity within a single object graph is important.
- In some specific algorithms where objects need to be distinguished by their identity rather than their logical equivalence.
- For detecting cyclic references.