Java 为什么存在 WeakHashMap,而没有 WeakSet?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4062919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:08:00  来源:igfitidea点击:

Why does exist WeakHashMap, but absent WeakSet?

javacollectionsgarbage-collectionweak-references

提问by Stan Kurilin

From J. Bloch

J. 布洛赫

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.

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

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

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

回答by mart

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

As seen in Collections.newSetFromMapdocumentation, passing a WeakHashMapto get a Set.

Collections.newSetFromMap文档中所示,传递 aWeakHashMap以获取Set.

回答by Stephen C

So, why there isn't any WeakSet in java collection framework?

那么,为什么java集合框架中没有WeakSet呢?

The only really correct answer to that is that we can't tell you why because we are not the people who made the design decisions. Only the Java designersknow why they made the decision1.

唯一真正正确的答案是我们无法告诉您原因,因为我们不是做出设计决策的人。只有Java 设计者知道他们为什么做出这个决定1



While there may be limited use-cases for WeakHashSet, part of the Java class library design philosophy was to avoid populating the class libraries with utility classes for all possible use-cases.

虽然 可能有有限的用例WeakHashSet,但 Java 类库设计理念的一部分是避免为所有可能的用例使用实用程序类填充类库。

There are a number of other class libraries which include collection types; Apache Commons Collections and Google Collections (aka Guava) are good examples. However, WeakHashSethasn't even "made the cut" for the Apache and Google libraries.

还有许多其他类库包括集合类型;Apache Commons Collections 和 Google Collections(又名 Guava)就是很好的例子。但是,WeakHashSetApache 和 Google 库甚至还没有“成功”。

And, of course, you can use Collections.newSetFromMapto wrap a WeakHashMapinstance.

而且,当然,您可以使用Collections.newSetFromMap来包装WeakHashMap实例。



1 - Debating the correctness of that decision is out of scope for StackOverflow. This is a Q&A site, not discussion forum.

1 - 争论该决定的正确性超出了 StackOverflow 的范围。这是一个问答网站,而不是论坛。

回答by Axel D?rfler

While you can indeed use Collections.newSetFromMap()to get a WeakSet, it's use cases are actually quite limited.

虽然您确实可以使用它Collections.newSetFromMap()来获取 WeakSet,但它的用例实际上非常有限。

If you want to implement something like String.intern()you might want to have a look at Guava's Interners.newWeakInterner()functionality instead.

如果你想实现类似的东西,String.intern()你可能想看看 Guava 的Interners.newWeakInterner()功能。