Iterator pattern

The iterator pattern provides to access contents of a collection without exposing its internal structure. It is also known as cursor.

advantages

  1. Access contents of a collection without exposing its internal structure.
  2. Uniform the interface for traversing different collection.
  3. Ability to have variations of collection traversal.
// from java source
public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove();
    void set(E e);
    void add(E e);
}

// List iterator of the ArrayList class
private class ListItr extends Itr implements ListIterator<E> {
    ListItr(int index) {
        super();
        cursor = index;
    }

    public boolean hasPrevious() { return cursor != 0; }
    public int nextIndex() { return cursor; }
    public int previousIndex() { return cursor - 1; }

    @SuppressWarnings("unchecked")
    public E previous() {
        checkForComodification();
        int i = cursor - 1;
        if (i < 0)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i;
        return (E) elementData[lastRet = i];
    }

    public void set(E e) {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.set(lastRet, e);
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    public void add(E e) {
        checkForComodification();

        try {
           int i = cursor;
           ArrayList.this.add(i, e);
           cursor = i + 1;
           lastRet = -1;
           expectedModCount = modCount;
         } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
         }
    }
}