All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jadex.collection.WeakSet Maven / Gradle / Ivy

There is a newer version: 5.0-alpha6
Show newest version
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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy