Why does exist WeakHashMap, but absent WeakSet?

Stan Kurilin picture Stan Kurilin · Oct 31, 2010 · Viewed 22.5k times · Source

From J. Bloch

A ... source of memory leaks is listeners ... The best way to ensure that callbacks are garbage collected promptly is to store only weak references to them, for instance, by storing them only as keys in a WeakHashMap.

So, why there isn't any WeakSet in the Java Collections framework?

Answer

mart picture mart · Oct 31, 2010
Set<Object> weakHashSet = Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>());

As seen in Collections.newSetFromMap documentation, passing a WeakHashMap to get a Set.