Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combo of IdentityHashMap and WeakHashMap

I need a Map implementation that shares properties of both IdentityHashMap and WeakHashMap (reference equality instead of equals() and weak references on keys).

What implementation do you recommend (it has to work on Android)?

like image 625
zduny Avatar asked Apr 07 '14 10:04

zduny


People also ask

What is WeakHashMap and IdentityHashMap?

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

Where do I use WeakHashMap?

If you have some objects that are reused often in your application, and their construction is expensive, and there are too many of them to keep them all in memory - - you use WeakHashMap. Put there the object which is not currently used. When this object is needed - get it out of the map.


1 Answers

If you're suggesting Guava, then new MapMaker().weakKeys().makeMap() would do the job directly, since weakKeys uses reference equality for keys.

The documentation of weakKeys says:

Specifies that each key (not value) stored in the map should be wrapped in a WeakReference (by default, strong references are used). Warning: when this method is used, the resulting map will use identity (==) comparison to determine equality of keys, which is a technical violation of the Map specification, and may not be what you expect.

like image 149
Louis Wasserman Avatar answered Sep 21 '22 18:09

Louis Wasserman