What is a WeakHashMap and when to use it? [duplicate]

What is a WeakHashMap and when should one be using it? What are the differences between a WeakHashMap and a HashMap?


Elements in a weak hashmap can be reclaimed by the garbage collector if there are no other strong references to the key object, this makes them useful for caches/lookup storage.

Weak reference are not restricted to these hash tables, you can use WeakReference for single objects. They are useful to save resource, you can keep a reference to something but allow it to be collected when nothing else references it. (BTW, a strong reference is a normal java reference). There are also weak references which tend not to be as readily collected as soft references (which don't tend to hang about for long after the last strong reference disappears)


As others have already pointed out, a weak reference provides a means for using an object as a key without creating a strong reference to it. This is useful in situations where you don't want to impair the JVM's ability to garbage collect the object, but yet still want the ability to track some aspect of the object, which makes a weak reference ideal for caching or storing metadata about the object.

I'd suggest reading "Understanding Weak References" (Oracle blog article), about strong vs. weak references in Java. Without an understanding of the difference, the data structure itself makes little sense.