Search code examples
javalistweak-references

How to remove a weakReference from a list?


I've got a list of weakReferences to objects in java. How do i write a method that gets the real object instance and removes it's weak reference from this list?

thanks.


Solution

  • It's not entirely clear what you mean, but I think you may want:

    public static <T> void removeReference(List<WeakReference<T>> list,
                                           T reference)
    {
        for (Iterator<WeakReference<T>> iterator = list.iterator();
             iterator.hasNext(); )
        {
            WeakReference<T> weakRef = iterator.next();
            if (weakRef.get() == reference)
            {
                iterator.remove();
            }
        }
    }