San Jose State University | CS 151 | Spring 2019

Homework 5

In this homework, you will provide implementations of the Iterator<Integer> interface for my solution (not yours) of the ArraySet and BitSet classes from Homework 4. (Why my solution? I want everyone to be familiar with it so I can ask questions about it in the midterm.)

Add an Iterator<Integer> iterator() method to the IntSet interface.

In ArraySet, add an inner class ArraySetIterator that implements Iterator<Integer:

public class ArraySet
{
   . . .
   private class ArraySetIterator implements Iterator<Integer>
   {
      public boolean hasNext() { . . . }
      . . .
   }

   public Iterator<Integer> iterator()
   {
      return new ArraySetIterator();
   }

   private int modCount;
   private int nextIndex;
   private boolean afterNext;
}

Do the same for the BitSet.

The ArraySet iterator should visit the elements in the order in which they are present in the elements array.

The BitSet iterator should visit the elements in increasing order.

You need to enforce the contract of the remove method. If it is called before next has been called, or immediately again after a call to remove, throw an IllegalStateException.

When a set is visited by an iterator and modified by an operation other than the iterator's remove, the next iterator operation should throw a ConcurrentModificationException. Add a field modCount to both the set and the iterator. Increment it with each mutation.

In the second part of this assignment, you will provide a functional interface IntSequence with a single abstract method next that returns the next element from the sequence or null if all elements have been visited. Provide a static method fromIterator that turns an Iterator<Integer> into an IntSequence, returning a lambda expression. Also provide a default method

default IntSequence alternate(IntSequence other)

that returns a sequence alternately taking elements from this and the other sequence, until both are exhausted. For example, if the first sequence returns values 1, 2, 4, 8, 11 and the second returns values 7, 5, 9, then you should return a sequence yielding 1, 7, 2, 5, 4, 9, 8, 11.

Also provide two unit test classes IteratorTest and SequenceTest with test cases of your choice.

Supply Javadoc comments as usual.

Make at least three Git commits.