taylorialcom/ DataStructures

Iterators

I like to iterate, it's great.

Iterator<T> iterator();

Revisiting the Simplified ArrayList<E> Example

    @Override
    public Iterator<E> iterator() {
        return new ArrayListIterator();
    }

    private class ArrayListIterator implements Iterator<E> {

        private int position;

        private boolean isLegalToRemove;

        private ArrayListIterator(){
            position = -1;
            isLegalToRemove = false;
        }

        @Override
        public boolean hasNext() {
            return size() > (position+1);
        }

        @Override
        public E next() {
            if(!hasNext()){
                throw new NoSuchElementException("No next element available");
            }
            isLegalToRemove = true;
            return array[++position];
        }

        @Override
        public void remove() {
            if(!isLegalToRemove){
                throw new IllegalStateException("Must call next() before remove()");
            }
            isLegalToRemove = false;
            ArrayList.this.remove(position--);
        }

    } // End of ArrayListIterator class

Enhanced for Loop: The foreach Loop

1

It's tough to take superhero seriously if it has a slash in its name, so I probably should have just said Nested class to the rescue OR Inner class to the rescue.

2

Hopefully you didn't notice that we didn't actually implement that method.