Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Iterable — a contract for traversing elements

java.lang.Iterable<T> enables an object to be used in an enhanced for loop. Its iterator() method supplies an iterator, while the default forEach() method applies an action to successive elements.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public interface Iterable<T>
Iterator<T> iterator()
default void forEach(Consumer<? super T> action)

java.lang.Iterable<T> lets an object be used in an enhanced for loop; T specifies the element type. It is a traversal contract, not a concrete container.

Iterable.iterator() returns an Iterator<T>. Distinguish the object providing iteration from the iterator tracking its progress: hasNext() checks whether an element is available, and next() retrieves it. With no element available, next() throws NoSuchElementException.

Iterable.forEach(Consumer<? super T> action) is a default method. It processes elements in iteration order, if specified. An action's exception stops processing and propagates to the caller; a null action causes NullPointerException. Do not modify the source in the action: behavior is unspecified unless the implementation defines an appropriate policy.

The example implements iterator() using the ordered list List.of("A", "B") and inherits forEach(). Each call to iterator() creates a new iterator here, so both traversals print both elements.

Examples

import java.util.Iterator;
import java.util.List;

public class Main implements Iterable<String> {
    @Override
    public Iterator<String> iterator() {
        return List.of("A", "B").iterator();
    }

    public static void main(String[] args) {
        Main letters = new Main();
        for (String letter : letters) {
            System.out.println("loop: " + letter);
        }
        letters.forEach(letter -> System.out.println("action: " + letter));
    }
}

Result

loop: A
loop: B
action: A
action: B

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources