Why does exist WeakHashMap, but absent WeakSet?

こ雲淡風輕ζ 提交于 2019-11-27 17:47:05
Martin v. Löwis

It's simple: there are use cases for WeakHashMap (in particular, the case where you want to annotate objects with additional properties), but there are no use cases for WeakSets.

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

As seen in Collections.newSetFromMap documentation, passing a WeakHashMap to get a Set.

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

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 decision1.


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.

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

And, of course, you can use Collections.newSetFromMap to wrap a WeakHashMap instance.


1 - Debating the correctness of that decision is out of scope for 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!