简体   繁体   English

为什么存在WeakHashMap,但缺少WeakSet?

[英]Why does exist WeakHashMap, but absent WeakSet?

From J. Bloch 来自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 . 内存泄漏的来源是监听器......确保回调被及时垃圾回收的最佳方法是仅存储对它们的弱引用,例如,通过仅将它们存储为WeakHashMap中的键。

So, why there isn't any WeakSet in the Java Collections framework ? 那么,为什么Java Collections框架中没有任何WeakSet?

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

As seen in Collections.newSetFromMap documentation, passing a WeakHashMap to get a Set . Collections.newSetFromMap文档中所示,传递WeakHashMap以获取Set

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 designers know why they made the decision 1 . 只有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. Apache Commons Collections和Google Collections(又名Guava)就是很好的例子。 However, WeakHashSet hasn't even "made the cut" for the Apache and Google libraries. 但是, WeakHashSet甚至没有为Apache和Google库“削减”。

And, of course, you can use Collections.newSetFromMap to wrap a WeakHashMap instance. 当然,您可以使用Collections.newSetFromMap来包装WeakHashMap实例。


1 - Debating the correctness of that decision is out of scope for StackOverflow. 1 - 辩论该决定的正确性超出了StackOverflow的范围。 This is a Q&A site, not discussion forum. 这是一个问答网站,而不是讨论论坛。

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()功能。

这很简单:有WeakHashMap用例(特别是在你想要注释具有附加属性的对象的情况下),但WeakSets没有用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM