package collections;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Implement a rotating iterator. The iterator should
 * accept an array list of iterators, and iterate over
 * them column-wise.
 * 
 * i.e If the following iterators are passed:
 * 
 * iterator_1 => [1]
 * iterator_2 => [2, 3]
 * iterator_3 => [4]
 * 
 * Then the rotating iterator will return the following
 * elements in sequential order:
 * 
 * 1, 2, 4, 3.
 */
public class RotatingIterator<T> implements Iterator<T> {

	private final ArrayList<Iterator<T>> iterators;
	private int rotatingIndex;
	private T nextItem;

	public RotatingIterator(ArrayList<Iterator<T>> iterators) {
		this.iterators = iterators;
		this.rotatingIndex = 0;
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		int count = 0;
		boolean itemFound = false;
		while (!itemFound && count < iterators.size()) {
			Iterator<T> iterator = iterators.get(rotatingIndex);
			if (iterator != null && iterator.hasNext()) {
				nextItem = iterator.next();
				itemFound = true;
			}

			rotatingIndex++;
			rotatingIndex %= iterators.size();
			count++;
		}

		return count != iterators.size();
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}

@@ -169,19 +169,16 @@
 r should
-%0A *
  accept 
@@ -193,16 +193,19 @@
  list of
+%0A *
  iterato
@@ -224,19 +224,16 @@
 ate over
-%0A *
  them co
@@ -317,19 +317,16 @@
 1 =%3E %5B1%5D
-%0A *
  iterato
@@ -338,19 +338,16 @@
 %3E %5B2, 3%5D
-%0A *
  iterato
@@ -416,19 +416,16 @@
 ollowing
-%0A *
  element
@@ -439,16 +439,19 @@
 quential
+%0A *
  order:%0A
@@ -1072,16 +1072,75 @@
 next();%0A
+%09%09%09%09// we need this because nextItem can possibly be null.%0A
 %09%09%09%09item

Add comment to rotating iterator