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?

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • Believe this is what you might be looking for: http://stackoverflow.com/a/4062950/717932 – dardo Oct 14 '13 at 19:05
  • possible duplicate of [Why does exist WeakHashMap, but absent WeakSet?](http://stackoverflow.com/questions/4062919/why-does-exist-weakhashmap-but-absent-weakset) – Oliver Charlesworth Oct 14 '13 at 19:06
  • 3
    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. – Barry Fruitman Oct 14 '13 at 20:12

1 Answers1

36

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.

Pavel
  • 4,912
  • 7
  • 49
  • 69
Njol
  • 3,271
  • 17
  • 32