import java.util.Iterator; /* An instance of this class is for iterating over the members of a ** set of integers (specifically, an instance of SetIntRange). ** ** @author R. McCloskey ** @version December 2022 */ public class SetIntRangeIterator implements Iterator { /* The iterator produced by this private class is such that the ** set's elements are guaranteed to be returned (by successive calls ** to next()) in ascending order. */ // instance variables // ------------------ private int currentMember; private SetIntRange theSet; /* Establishes the given set (s) as the one whose members ** are to be iterated over. */ public SetIntRangeIterator(SetIntRange s) { theSet = s; advance(theSet.floor()); } /* Reports whether or not there are any more members of 'theSet' to ** be returned via calls to next(). */ public boolean hasNext() { return currentMember <= theSet.ceiling(); } /* Returns the smallest-valued member of 'theSet' that has not yet ** been returned by next(). ** pre: hasNext() */ public Integer next() { int result = currentMember; advance(currentMember+1); return result; } /* The remove operation is not supported. */ public void remove() { throw new UnsupportedOperationException(); } // private method // -------------- /* Finishes with 'currentMember' being equal to the smallest-valued ** member of 'theSet' that is not less than 'candidate'. In the case ** that no such number exists, 'currentMember' is set to one more than ** theSet.ceiling(). */ private void advance(int candidate) { final int ceiling = theSet.ceiling(); while (candidate <= ceiling && !theSet.isMemberOf(candidate)) { candidate++; } currentMember = candidate; } }