26

相当于? _ HashSet<WeakReference<T>>_ 也就是说,条目不再被引用时会被自动删除吗?SetWeakHashMap<T>

如果不是,什么是等价物?

4

1 回答 1

33

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.

于 2013-10-15T19:27:19.533 回答