The Iterator Pattern in Java

Introduction to the Iterator Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

The Iterator pattern is used extensively in Java. It provides a standard way to iterate through a collection of objects.

Implementation of Iterator Pattern in Java

In the Basic Algorithms and Data Structures we have covered the Iterator ADT, which is interpreted as an interface in Java. So we will do a quick example here, say we provide a standard way to traverse an array of int elements. First we create the Iterator.java in src folder:

public interface Iterator {
  boolean hasNext();
  int next();
}

Next we create an Array class:

public class Array{
  private final int[] nums = {5, 42, 3, 6, 9};
  public Iterator getIterator() {
    return new ArrayIterator();
  }
  private class ArrayIterator implements Iterator{
    int index;
    public boolean hasNext() {
      return index < nums.length;
    }
    public int next() {
      if (this.hasNext()) return nums[index++];
      else throw new RuntimeException(
          "Out of ranges");
    }
  }
}

The class provides an Iterator object that allows clients to iterate through the array nums. Now in Test.java:

public class Test {
  public static void main(String[] args){
    Array array = new Array();
    Iterator iterator = array.getIterator();
    while (iterator.hasNext()){
      System.out.println(iterator.next());
    }
  }
}

Clearly the output will be:

5
42
3
6
9

The Iterator pattern is used extensively in Java Collections.

Leave a Reply