import java.util.*; /** * Implementation of IBoundedSet that adapts an ISet. * @author Jeff Raab */ public class BoundedSetAdapter implements IBoundedSet { /** ISet used to hold elements of this. */ protected ISet proxySet; /** Maximum size of this. */ protected int bound; /** * Constructs a bounded set of the given maximum size * that uses the given set to hold its elements. * @param aSize maximum size for the bounded set * @param aSet set to use to hold elements of the bounded set * @throws RuntimeException if the given maximum size is negative or * if the given set is too large */ public BoundedSetAdapter(int aSize, ISet aSet) { if (aSize < 0) { throw new RuntimeException("Size cannot be negative"); } this.bound = aSize; if (aSet.size() > getMaximumSize()) { throw new RuntimeException("Proxy set too large"); } this.proxySet = aSet; } /** * Adds the given object to this. * @param anObject object to be added * @throws RuntimeException if the size of this is at its maximum */ public void add(Object anObject) { if (size() == getMaximumSize()) { throw new RuntimeException("Bounded set is at maximum size"); } proxySet.add(anObject); } /** * Removes the given object from this. * @param anObject object to be removed */ public void remove(Object anObject) { proxySet.remove(anObject); } /** * Sets this to its union with the given set. * @param aSet set with which to union */ public void union(ISet aSet) { int toAdd = 0; for (Enumeration e = aSet.elements(); e.hasMoreElements(); ) { if (!this.contains(e.nextElement())) { toAdd++; } } if (size() + toAdd > getMaximumSize()) { throw new RuntimeException("Union will violate the maximum size"); } proxySet.union(aSet); } /** * Sets this to its intersection with the given set. * @param aSet set with which to intersect */ public void intersection(ISet aSet) { proxySet.intersection(aSet); } /** Returns the number of objects in this. */ public int size() { return proxySet.size(); } /** * Returns whether or not this contains the given object. * @param anObject object to compare with contents of this */ public boolean contains(Object anObject) { return proxySet.contains(anObject); } /** * Returns whether or not the given object equals this. * @param anObject object to compare with this */ public boolean equals(Object anObject) { BoundedSetAdapter aBSA = (BoundedSetAdapter)anObject; return this.proxySet.equals(aBSA.proxySet); } /** Returns an item in this. */ public Object item() { return proxySet.item(); } /** Returns an enumeration of the contents of this. */ public Enumeration elements() { return proxySet.elements(); } /** Returns the maximum size of this. */ public int getMaximumSize() { return bound; } }