Skip to content
Veltoryx Technologies
ProLesson 7.3Intermediate7 min readUpdated 31 October 2026

Iterator Pattern

Learn how to walk through the items of any collection without knowing how it stores them, build your own iterators including a lazy paged one, and avoid the ConcurrentModificationException trap.

When you read a book, you use a bookmark. The bookmark remembers where you are. You do not need to know how the book is printed or bound. You just say "next page" and the bookmark moves forward, until there are no more pages. Two readers can use two bookmarks in the same book at the same time without disturbing each other.

The Iterator pattern gives collections a bookmark. An iterator is a small object that remembers a position in a collection and lets you ask "is there another item?" and "give me the next one". The code that uses it does not need to know whether the items sit in an array, a linked list, a tree or a database. This pattern is so useful that it is built into Java itself: every for-each loop you have ever written uses it.

01The problem: the loop depends on how the data is stored

Suppose you write a BookShelf class. A first version might expose its internal list so that callers can loop over it:

Before: callers must know the inside of the shelf
public class BookShelf {
    private final Book[] books = new Book[100];
    private int count = 0;

    public void add(Book book) { books[count++] = book; }
    public Book[] getBooks()   { return books; }
    public int size()          { return count; }
}

// A caller must know it is an array, and how many items are really in it
for (int i = 0; i < shelf.size(); i++) {
    print(shelf.getBooks()[i]);
}

This is fragile:

  • The caller knows that the shelf is an array and uses index numbers.
  • If the shelf later changes to a List, or a tree sorted by title, every loop in the program breaks.
  • The shelf exposes its internal array, so any caller can change or damage it.
  • Every collection type needs its own style of loop, so you cannot write one method that works on all of them.

Loading the rest of the lesson…