/** * SetImplementation implements interface SetInterface * * @author rpj * @version 12ix08 */ import java.util.*; public class SetImplementation implements SetInterface { private HashSet hs = new HashSet(); /** Adds one element to this set, ignoring duplicates. */ public void add (T element) { hs.add(element); } /** Removes and returns a random element from this set. */ public T removeRandom () throws EmptySetException { if (hs.isEmpty()) throw new EmptySetException(); else { int stopHere = (int)(Math.random() * hs.size()); int i = 0; for (T e : hs) if (i++ == stopHere) { hs.remove(e); return(e); } return null; // should never happen } } /** Removes and returns the specified element from this set. */ public T remove (T element) throws NoSuchElementException { if (!hs.contains(element)) throw new NoSuchElementException(); hs.remove(element); return element; } /** Returns true if this set contains the parameter */ public boolean contains (T target) { return hs.contains(target); } /** Returns true if this set and the parameter contain exactly the same elements */ public boolean equals (SetInterface set) { return (this.subset(set) && set.subset(this)); } /** Returns true if this set contains no elements */ public boolean isEmpty() { return hs.isEmpty(); } /** Returns the number of elements in this set */ public int size() { return hs.size(); } /** Returns an iterator for the elements in this set */ public Iterator iterator() { return hs.iterator(); } /** Returns a string representation of this set */ public String toString() { String ret = ""; for (T e : hs) ret += e.toString()+" "; return ret; } /** Forms the union of this set and the parameter */ public void union (SetInterface set) { Iterator it = set.iterator(); while(it.hasNext()) hs.add(it.next()); } /** Forms the intersection of this set and the parameter */ public void intersection(SetInterface set) { HashSet toGo = new HashSet(); for (T e : hs) if (!set.contains(e)) toGo.add(e); for (T go : toGo) hs.remove(go); } /** Returns true if this set is a subset of the parameter */ public boolean subset(SetInterface set) { for (T e : hs) if (!set.contains(e)) return false; return true; } /** Forms the set difference of this and the parameter. * * That is the set of elements in here but not in the parameter set */ public void diff(SetInterface set) { HashSet toGo = new HashSet(); for (T e : hs) if (set.contains(e)) toGo.add(e); for (T go : toGo) hs.remove(go); } }