Set equivalent of WeakHashMap?
Asked Answered
T

1

29

Is HashSet<WeakReference<T>> the Set equivalent of WeakHashMap<T>? That is, will entries be automatically deleted when they are no longer referenced?

If not, what is the equivalent?

Tenderhearted answered 14/10, 2013 at 19:2 Comment(3)
Believe this is what you might be looking for: https://mcmap.net/q/240975/-why-does-exist-weakhashmap-but-absent-weaksetBouleversement
possible duplicate of Why does exist WeakHashMap, but absent WeakSet?Morse
This question is not a duplicate. The other question attempts to answer why there is no WeakSet. It doesn't provide a Set equivalent, nor does it answer whether my example above counts as an equivalent.Tenderhearted
W
37

No, if an object referenced by one of the WeakReferences in the set gets garbage-collected, the WeakReference will still be included in the set and will not be removed automatically, but their referent will be null. A WeakHashMap uses additional code to remove the weakly referenced keys from the map when they're garbage-collected.

A set equivalent of a WeakHashMap is:

Set<T> set = Collections.newSetFromMap(new WeakHashMap<T, Boolean>()); 

As a HashSet also uses a HashMap internally.

BTW: A WeakReference is just an object pointing to an object which may be garbage-collected despite the reference held by the WeakReference. The WeakReference itself will not be garbage-collected until it is not strongly referenced anywhere anymore just like all other objects.

Weaks answered 15/10, 2013 at 19:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.