views:

549

answers:

1

A couple of questions regarding Java's WeakReference and Collections:

  1. Is there a library out there that implements Java's various data-set interfaces (eg Collection, List, Set, Queue etc) with WeakReference transparently? Like WeakHashMap is for the HashMap interface?

  2. Or is the common solution to simply create normal Collections and then use some sort of trick with compareTo or a Comparator or something to make searching the collection work correctly?

I basically would like this:

public interface WeakCollection<E> extends Collection<E> {}

But the contract for the interface is that the references to E are stored weakly. Obviously I do not have a problem with get(int index) returning null when that object has gone away etc, but I would like the contains(E e) function and other items like it to work properly.

I'm just trying to avoid the "not invented here" trap and ensuring that if I do implement this myself that its the simplest solution possible.

+2  A: 

JBoss has a WeakSet. In Java 6, you can also do

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

Also I found a WeakArrayList that's LGPL if that helps.

Mr. Shiny and New
Oh nice that trick with Collections is cool, definitely useful.
Petriborg