Could anyone please tell what are the important use cases of IdentityHashMap
?
This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2).
HashMap uses object equality to compare the key and values. IdentityHashMap uses reference equality to compare the key and values.
What is the premise of equality for IdentityHashMap? Explanation: IdentityHashMap is rarely used as it violates the basic contract of implementing equals() and hashcode() method. Sanfoundry Certification Contest of the Month is Live.
The IdentityHashMap, WeakHashMap, and EnumMap all are the classes in java collection that implements the Map interface.
Whenever you want your keys not to be compared by equals
but by ==
you would use an IdentityHashMap. This can be very useful if you're doing a lot of reference-handling but it's limited to very special cases only.
The documentations says:
A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With