Why does exist WeakHashMap, but absent WeakSet?

后端 未结 3 1502
名媛妹妹
名媛妹妹 2020-12-04 15:29

From J. Bloch

A ... source of memory leaks is listeners ... The best way to ensure that callbacks are garbage collected promptly is to store o

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 15:45

    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.

提交回复
热议问题