On this page:
10.1 ???
Iterators
Combining Iterators
Iterating Forever
8.5

Lab 10: Iterators and Iterables

Goals: Practice with Iterators and Iterable

Submission: Submit your solutions to zipStrict, zipLists and concat in handins. You may submit your solution to cycle for extra credit. To earn the extra credit, cycle must be correct and well-tested. You may define these methods in a class named IteratorUtils. Your solutions are due at the end of your lab period and will be submitted individually although you may work with your partner on this. Remember that you need to be present in lab to submit!

10.1 
Iterators

Given the pair class:

class Pair<L, R> {
L left;
R right;
 
Pair(L left, R right) {
this.left = left;
this.right = right; }
}

Define a method with the following signature:
<X, Y> Iterator<Pair<X,Y>> zipStrict(ArrayList<X> arr1, ArrayList<Y> arr2)

The method should return an Iterator of pairs of corresponding elements. If the lists are of different sizes, an exception should be thrown.

Define a method with the following signature:
<X, Y> Iterator<Pair<X,Y>> zipLists(ArrayList<X> arr1, ArrayList<Y> arr2)

The method should return an Iterator of pairs of corresponding elements. If the lists are of different sizes, only return pairs up to the size of the shorter one.

Combining Iterators

Define a method with the following signature:
<T> Iterator<T> concat(Iterator<T> iter1, Iterator<T> iter2)

The method should produce a new Iterator that concatenates the two Iterators (similar to append on lists). Note that this method should terminate even if iter1 or iter2 is an infinitely large Iterator.

Iterating Forever

Define a method with the following signature:
<T> Iterator<T> cycle(Iterable<T> iterable)

The method should produce an iterator that cycles through the elements of iterable forever. For example, if the iterable were the list 1,2,3, then the iterator produced should be the iterator of 1,2,3,1,2,3,1,2,3,1,2,3.... Note that this method should terminate even if iterable’s iterator is infinite.

Hint: Look carefully at the signature above, and recall our discussion in class about what to do to “start over from the beginning”...

Warning: The iterator produced won’t always have a new element to return. When wouldn’t it? What (pretty tiny) test case could you write to trigger this behavior?