/** * This class implements a subset from an existing set. It's slow and * inefficient because I didn't have time to write anything better. * @author Gary Yngve * @version 2/10/06 */ // TODO: WRITE JAVADOC import java.util.Comparator; import java.util.NoSuchElementException; public class BasicOrderedSubTreeSet implements BasicOrderedSet { BasicOrderedSet originalSet; Object min, max; private BasicOrderedSubTreeSet() {} public BasicOrderedSubTreeSet(BasicOrderedSet originalSet, Object min, Object max) { this.originalSet = originalSet; this.min = min; this.max = max; } public boolean contains(Comparable o) { if (originalSet.comparator().compare(o,min) < 0 || originalSet.comparator().compare(o,max) >= 0) return false; else return originalSet.contains(o); } public boolean add(Comparable o) { if (originalSet.comparator().compare(o,min) < 0 || originalSet.comparator().compare(o,max) >= 0) throw new IllegalArgumentException("inserting out of range"); return originalSet.add(o); } public int size() { int count = 0; for(BasicSetIterator it = iterator(); it.hasNext(); ) { it.next(); count++; } return count; } public boolean remove(Comparable o) { throw new UnsupportedOperationException(); } public BasicOrderedSet subSet(Object newmin, Object newmax) { if (originalSet.comparator().compare(newmin,newmax) >= 0) throw new IllegalArgumentException("inverted range"); if (originalSet.comparator().compare(newmin,min) < 0) throw new IllegalArgumentException("lower bound too low"); if (originalSet.comparator().compare(max,newmax) < 0) throw new IllegalArgumentException("upper bound too high"); return new BasicOrderedSubTreeSet(originalSet, newmin, newmax); } public Comparator comparator() { return originalSet.comparator(); } public BasicSetIterator iterator() { return new BasicOrderedSubTreeSetIterator(); } private class BasicOrderedSubTreeSetIterator implements BasicSetIterator { BasicSetIterator it; boolean cached; boolean cachedBool; Comparable cachedObj; BasicOrderedSubTreeSetIterator() { it = originalSet.iterator(); } public boolean hasNext() { if (cached) return cachedBool; cached = true; while(it.hasNext()) { Comparable o = it.next(); if (originalSet.comparator().compare(o,min) >= 0 && originalSet.comparator().compare(o,max) < 0) { cachedObj = o; cachedBool = true; return true; } } cachedBool = false; return false; } public Comparable next() { if (!hasNext()) throw new NoSuchElementException(); cached = false; return cachedObj; } } }