![]() |
VOOZH | about |
The IdentityHashMap, WeakHashMap, and EnumMap all are the classes in java collection that implements the Map interface. But there are few differences exists between them.
1. IdentityHashMap: The IdentityHashMap implements the Map interface. It follows reference-equality in place of object-equality when comparing keys (and values). This class is used when the user requires the objects to be compared via reference. It is not synchronized and must be synchronized externally. The iterators in this class are fail-fast, throw ConcurrentModificationException in an attempt to modify while iterating.
Working of IdentityHashMap:
IdentityHashMap size : 5
Initial identity hash map: {10=Geeks, 40=Welcomes, 50=You, 30=Geeks, 20=4}
Key = 10, Value = Geeks
Key = 40, Value = Welcomes
Key = 50, Value = You
Key = 30, Value = Geeks
Key = 20, Value = 42. WeakHashMap: WeakHashMap is the implementation of the Map interface that stores only weak keys. In WeakHashMap, we can store only weak references of its key that allows a key-value pairs to be garbage collected when its key is no longer in ordinary use. WeakHashMap is the HashTable based implementation, but it is not synchronized. It allows you to store both null key and null values.
Working of WeakHashMap:
WeakHashMap is : {5=you, 4=welcomes, 3=geeks, 2=4, 1=geeks}
Yes welcomes exist
Yes 3 exist
key Set : [5, 4, 3, 2, 1]
Values : [you, welcomes, geeks, 4, geeks]
Empty WeakHashMap: {}3. EnumMap: EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. Few important features of EnumMap are as follows:
Working of EnumMap:
Size of EnumMap: 4 January 31 February 28 March 31 April 30
Difference between IdentityHashMap, WeakHashMap, and EnumMap:
| PROPERTIES | IdentityHashMap | WeakHashMap | EnumMap |
|---|---|---|---|
| References | IdentityHashMap stores strong key reference. | WeakHashMap stores the weak key reference. | EnumMap stores the strong key reference. |
| Search and get the values | It uses equality operator (==) to search and get the values. | It uses equals() method for that purpose. | It also uses equals() method for that purpose. |
| Keys | It allows to store any type of keys. | It also allows to store any type of keys. | It allows to store only enum type keys. |
| Underlined data structure | It uses the array as an underlined data structure. | It uses the HashTable as an underlined data structure. | It uses the array as an underlined data structure. |
| Iterator | Iterator used in IdentityHashMap is Fail-fast. | Iterator used in WeakHashMap is Fail-fast. | Iterator used in EnumMap is weakly consistent. |
| Null Values | It allows to store null values. | It allows to store null values. | It doesn't allow to store null values |