Java Program to Implement IdentityHashMap API
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:
- The main difference between HashMap vs IdentityHashMap is that IdentityHashMap uses the equality operator “==” for comparing keys and values inside Map while HashMap uses equals(obj) method for comparing keys and values.
- Since IdentityHashMap doesn’t use equals(obj), its comparatively faster than HashMap for object with expensive equals(obj) and hashCode().
- One more difference between HashMap and IdentityHashMap is the immutability of the key. One of the basic requirements of safety, when we store objects in HashMap, is keys need to be immutable, IdentityHashMap doesn’t require keys to be immutable as it does not rely on equals(obj) and hashCode().
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).
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
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.