Java programming language logo

Iterator Design Pattern

The Iterator pattern is used for traversing through an aggregate object to get access to its elements sequentially without the need to know the aggregation’s structure.

The iterator encapsulates an aggregate object and the iteration logic. It also provides remove operation from the aggregation.

Iterator is a behavioral pattern.

Example

Let’s see a Java example for the Iterator pattern.

The next iterator class implement the Iterator interface that is found in the java.util package. The ArrayIterator class takes an array at instantiation. The type of the array can be any type of objects because ArrayIterator is a generic class.

It also has a index field to keep track of the iteration. It is incremented by one at every iteration step.

The hasNext method returns with true if the iteration has more elements. The next method returns the next element from the array.

The remove method removes the current element from the array. Actually, it shifts the elements to left from the actual index, so the current element will be overwritten, and no gaps arises in the array.


package com.programcodex.designpatterns.iterator;

import java.util.Iterator;

public class ArrayIterator<E> implements Iterator<E> {
    
    private final E[] array;
    private int index = 0;

    public ArrayIterator(E[] array) {
        this.array = array;
    }

    @Override
    public boolean hasNext() {
        return index < array.length && array[index] != null;
    }

    @Override
    public E next() {
        return array[index++];
    }

    @Override
    public void remove() {
        if (index <= 0) {
            throw new IllegalStateException("There’s no selected item.");
        }

        if (array[index - 1] != null) {
            for (int i = index - 1; i < array.length - 1; i++) {
                array[i] = array[i + 1];
            }

            array[array.length - 1] = null;
            index--;
        }
    }
}

And we are done. It’s time to run these things.

First, the Iterator is used with a String array, after that with an Integer array in the printArray generic method. Finally, some of the Integer array elements get removed.


package com.programcodex.designpatterns.iterator;

import java.util.Iterator;

public class TestIterator {

    public static void main(String[] args) {
        System.out.println("Iterate through Strings:\n");
        String[] arrayStr = {"Orange", "Apple", "Banana", "Grapefruit", "Grapes"};
        printArray(arrayStr);

        System.out.println("\nIterate through Integers:\n");
        Integer[] arrayInt = {1, 2, 3, 98, 99, 100};
        printArray(arrayInt);

        System.out.println("\nRemove odd numbers.");

        for (Iterator<Integer> it = new ArrayIterator<>(arrayInt); it.hasNext();) {
            Integer num = it.next();
            if (num % 2 != 0) {
                it.remove();
            }
        }

        System.out.println("After the remove:\n");
        printArray(arrayInt);
    }

    private static <T> void printArray(T[] arrayStr) {
        Iterator<T> it = new ArrayIterator<>(arrayStr);
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

The output of the above test class:

The Iterator Design Pattern