Iterators

Table of Contents

1. Enhanced For Loop

The enhanced for loop, or the for each loop, allows us to easily iterate over objects in some data structure without having to index each explicitly:

Set<Integer> javaset = new HashSet<>();
javaset.add(5);
javaset.add(23);
javaset.add(42);
for (int i : javaset) {
    System.out.println(i);
}

However, this doesn’t work by default on any of our own, custom classes. Let’s strip away the magic so we can build our own classes that also support this enhanced for loop.

2. Iterator

The enhanced for loop uses an iterator that is obtained by calling a .iterator() method on the object, which should return an object of type Iterator<T>. The Iterator interface contains the hasNext method, which tells us if there are more values, and next, which gets the next value:

Set<Integer> javaset = new HashSet<>();
javaset.add(5);
javaset.add(23);
javaset.add(42);
Iterator<Integer> seer = javaset.iterator();
while (seer.hasNext()) {
    System.out.println(seer.next());
}

2.1. Iterable

Adding this iterator() method allows our own classes to support this type of iteration, but the enhanced for loop would still not work. This is because Java needs a way of knowing our class supports this method.

Therefore, we need to implement Iterable<T>, which is an interface that includes the iterator() method.

Last modified: 2026-02-11 13:29