![]() |
VOOZH | about |
The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. This class is used when the user requires the objects to be compared via reference. It belongs to java.util package. It was later added in Java 1.4
The main difference between IdentityHashMap and HashMap in java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals(obj) and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator “==” to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check instead of logical equality.
Differences between IdentityHashMap and HashMap are as follows:
Example 1:
Size of HashMap is : 2 Size of IdentityHashMap is : 4
Implementation: HashMap uses hashCode() to find bucket location. IdentityHashMap doesn't use hashCode(), instead it uses System.identityHashCode(object).
Example 2:
Before modifying keys : Does Groovy language exists in HashMap? Yes Does Groovy language in IdentityHashMap? Yes After modifying keys : Does Groovy language exists in HashMap? No Does Groovy language exists in IdentityHashMap? Yes
Output explanation:
It is clear from the output that once the programming language object is changed, which is key in both HashMap and IdentityHashMap, we are unable to retrieve an object in the case of HashMap but are able to retrieve when you use IdentityHashMap because the former uses equals() method which returns false once the value is changed and latter uses "==" operator which returns true because in both cases the object is the same in heap.