tags:

views:

698

answers:

5

Could anyone please tell important use cases of Identity HashMap?

+5  A: 

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 doint a lot of reference-handling but it's limited to very special cases only.

Benedikt Eger
The behavior of the comparison is the ticket here. I have used "Identity" HashMaps for storing meta-data that should be associated with a particular object. The value equality of the objects possibly being the same. However, care must be taken to ensure the original is preserved as long as the [direct] lookup is required -- and care must be taken to avoiding "leaking" memory.
pst
Also, because the identity invariant (o == o => true, for any o), IdentityHashMap can be used *even if the key objects are mutated*. But you aren't using mutable keys... are you? (Perhaps I should go sit in a corner and cry.)
pst
+10  A: 

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.

sris
+3  A: 

This is a practical experience from me:

IdentityHashMap leaves a much smaller memory footprint compared to HashMap for large cardinalities.

rfang
+1  A: 

One case where you can use IdentityHashMap is if your keys are Class objects. This is about 33% faster than HashMap for gets! It probably uses less memory too.

NateS
+1  A: 

HashMap creates Entry objects every time you add an object, which can put a lot of stress on the GC when you've got lots of objects. In a HashMap with 1,000 objects or more, you'll end up using a good portion of your CPU just having the GC clean up entries (in situations like pathfinding or other one-shot collections that are created and then cleaned up). IdentityHashMap doesn't have this problem, so will end up being significantly faster.

See a benchmark here: http://www.javagaming.org/index.php/topic,21395.0/topicseen.html

Eli
Hehe, I'm the same Nate.
NateS
:-) Aha! Go JGO.
Eli