Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases for IdentityHashMap

Tags:

java

Could anyone please tell what are the important use cases of IdentityHashMap?

like image 698
Isabel Jinson Avatar asked May 08 '09 06:05

Isabel Jinson


People also ask

What is the main use 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).

What is difference between HashMap and IdentityHashMap in Java?

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?

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.

What is WeakHashMap and IdentityHashMap?

The IdentityHashMap, WeakHashMap, and EnumMap all are the classes in java collection that implements the Map interface.


2 Answers

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.

like image 51
B.E. Avatar answered Sep 20 '22 02:09

B.E.


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.

like image 40
sris Avatar answered Sep 23 '22 02:09

sris