来自 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
.
这篇关于为什么存在WeakHashMap,却没有WeakSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!