jadex.collection.WeakSet Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collection Show documentation
Show all versions of collection Show documentation
Provides extensions to Java collection classes
package jadex.collection;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.ref.ReferenceQueue;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A weak set for entries that will be automatically removed when
* no references to them are existing any more.
*/
public class WeakSet extends AbstractSet implements Serializable, Cloneable
{
//-------- attributes ---------
/** The set which will be used for element storage. */
protected transient Set set;
/** The reference queue used to get object removal notifications. */
protected transient ReferenceQueue queue = new ReferenceQueue();
//-------- constructors ---------
/**
* Construct a WeakSet based on a HashSet.
*/
public WeakSet()
{
this.set = new HashSet();
}
//-------- methods ---------
/**
* Return the size of the set.
* @return The size of the set.
*/
public int size()
{
expungeStaleEntries();
return set.size();
}
/**
* Return an iteration over the elements in the set.
* @return An iteration over the elements in the set.
*/
public Iterator iterator()
{
// todo: is this implementation sound???
expungeStaleEntries();
return new Iterator()
{
Iterator iter = set.iterator();
Object next = null;
public boolean hasNext()
{
while(next==null && iter.hasNext())
this.next = ((WeakObject)iter.next()).get();
return next!=null;
}
public Object next()
{
if(!hasNext())
throw new NoSuchElementException();
// hasNext() has the side-effect of setting the next element!
Object ret = this.next;
this.next = null;
return ret;
}
public void remove()
{
throw new UnsupportedOperationException("Remove method not supported for iterator of weak set.");
}
};
}
/**
* Convert the set to an array.
*/
// Overriden, because AbstractCollection implementation relies on constant size.
public Object[] toArray()
{
Object[] result = new Object[size()];
int i = 0;
Iterator it = iterator();
for(; it.hasNext(); i++)
result[i] = it.next();
// Reallocate array, when some elements have been garbage collected (shouldn't happen often).
if(i