Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Iterable.iterator(): repeated vs. independent traversals

`Iterable.iterator()` returns an iterator. Support for successive passes does not guarantee that overlapping passes are independent or that each call returns a new iterator object.

Version: Java SE 21

Syntax

Iterator<T> iterator();

Iterable.iterator() is a no-argument instance method on java.lang.Iterable<T>. It returns a java.util.Iterator<T> for stepping through elements of type T. The Iterable provides the elements to traverse; the Iterator tracks the position of one particular traversal.

An implementation can allow a new pass after the previous one finishes without supporting overlapping passes. For example, it could reset and reuse the same iterator. If you want to support independent traversals, as in nested loops, one simple approach is to return a fresh iterator with its own position initialized at the start on each call. With a shared cursor, advancing one traversal would affect the other. Repeatability is not guaranteed by the general Iterable contract: a second attempt to obtain an iterator from a DirectoryStream throws IllegalStateException.

When traversing manually, check hasNext() before calling next(). The former checks whether an element remains without consuming it; the latter returns it and advances the position. Once exhausted, next() throws NoSuchElementException. An enhanced for loop over an Iterable calls iterator() once at the start, then uses hasNext() and next(). For arrays, it uses indexes instead.

Examples

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Main {
    static final class OneToThree implements Iterable<Integer> {
        @Override
        public Iterator<Integer> iterator() {
            return new Iterator<Integer>() {
                private int nextValue = 1;

                @Override
                public boolean hasNext() {
                    return nextValue <= 3;
                }

                @Override
                public Integer next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException();
                    }
                    return nextValue++;
                }
            };
        }
    }

    public static void main(String[] args) {
        Iterable<Integer> numbers = new OneToThree();
        Iterator<Integer> a = numbers.iterator();
        Iterator<Integer> b = numbers.iterator();

        System.out.println("a: " + a.next());
        System.out.println("a: " + a.next());
        System.out.println("b: " + b.next());

        for (int number : numbers) {
            System.out.println("for: " + number);
        }
    }
}

Result

a: 1
a: 2
b: 1
for: 1
for: 2
for: 3

`a` returns 1 and then 2, but `b` still starts at 1. The enhanced `for` loop obtains a third iterator and prints 1 through 3.

Related lessons

  • Java · Lesson 24 · Intermediate · Version: 2

Sources