SWE/CS 332 In Class Exercise Number 13
October 11, 2017

Names:
Goal: Mid-semester recap of key course topics, namely immutability, state, correctness, and refinement.

Consider the Java Iterator<E> interface:

public interface Iterator <E> {
   public boolean hasNext();
   public E next();        // throws NoSuchElementException
   public void remove();   // throws IllegalStateException
}
You might find it helpful to visit the Java documentation for this interface.

Note that all 3 methods are undefined if the underlying state of the collection changes during the iteration. Some java.util refinements of (i.e. subtypes of) Iterator replace this precondition with the defined behavior of ConcurrentModificationException. Question 0 (Look ahead question to next class topic): Is this "correct"? How do you think about this question?

Now, on to the main event:

  1. Design an immutable version of the Iterator<E> interface. Consider only Liskov's guidelines for immutability. Call the resulting interface IIterator<E>



    Things to think about:
    • What is the contract for hasNext()?

    • What happens with next()? What's the contract?

    • How is remove() handled? What evidence can you provide to justify your answer?

    • Does transforming the precondition into ConcurrentModificationException work for IIterator? Again, what evidence can you provide to justify your answer?

  2. Exercise the immutable iterator with some sample client code. Specifically, suppose you have a collection with Strings "cat", "dog", and "fox". Develop two parallel examples, one with the mutable iterator, and one with the immutable iterator. Access this collection with your iterators, and identify the abstract states of all relevant objects at each stage of your computation.









  3. Revisit the remove() and ConcurrentModificationException questions. For the former, what is the behavior of two successive remove() calls? For the latter, what is the behavior of two successive next() or hasNext() calls split by a call to a mutator on the underlying collection?







  4. Would it be safe to share immutable iterator objects among a number of threads?