import java.util.*; public class CircularList extends AbstractCollection implements Iterator { private final Object [] elements; private int current = -1; private int nElements; private final static Object DESTROYED = new Object(); public CircularList (Object [] elements) { this.elements = new Object[elements.length]; System.arraycopy(elements, 0, this.elements, 0, elements.length); nElements = elements.length; } public int size() { return nElements; } /** Be Careful, this method always returns the same instance of Iterator for a given instance of CircularList */ public Iterator iterator() { return this; } public boolean hasNext() { return nElements != 0; } public Object next() { Object o = DESTROYED; if (nElements == 0) { throw new NoSuchElementException(); } while (o == DESTROYED) { current = (current + 1) % elements.length; o = elements[current]; } return o; } public void remove() { if (nElements == 0 || current == -1 || elements[current] == DESTROYED) throw new IllegalStateException(); elements[current] = DESTROYED; } public static void main(String [] args) { CircularList cl = new CircularList(args); try { cl.remove(); } catch (IllegalStateException e) { System.out.println("Cannot use remove() before any next()"); } cl.next(); cl.next(); cl.next(); System.out.println("Forward three times"); Iterator it = cl.iterator(); for (int i = 0; i < 10; ++i) System.out.print(it.next() + " "); System.out.println(); System.out.println("Remove " + cl.next()); cl.remove(); try { cl.remove(); } catch (IllegalStateException e) { System.out.println("Cannot use two consecutive remove()"); } System.out.println("Remove " + cl.next()); cl.remove(); for (int i = 0; i < 10; ++i) System.out.println(it.next()); } }