为什么存在WeakHashMap,却没有WeakSet?

来自 J.布洛赫

... 内存泄漏的来源是听众... 最好的方法来确保回调被垃圾收集及时是只存储弱对它们的引用,例如,通过仅将它们作为键存储在WeakHashMap.

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.

那么,为什么 Java Collections 框架中没有 WeakSet?

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

推荐答案

Collections.newSetFromMap

Set<Object> weakHashSet = 
    Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>()
    );

Collections.newSetFromMap 文档,传递一个 WeakHashMap 获取 Set.

相关文章