为什么存在 WeakHashMap,而没有 WeakSet? [英] Why does exist WeakHashMap, but absent WeakSet?

查看:13
本文介绍了为什么存在 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 集合框架中没有任何 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆