Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Java iterator methods: hasNext(), next(), and remove()

Check whether an iterator has another element, retrieve it, and optionally remove it. Distinguish iterator exhaustion, an invalid call sequence, and unsupported removal.

Version: Java SE 21

Syntax

java.util.Iterator<E>
boolean hasNext()
E next()
default void remove()

The Java methods Iterator.hasNext/next/remove serve three different purposes. On java.util.Iterator<E>, hasNext() returns true if another element remains and false otherwise. It checks availability without retrieving an element or advancing the iterator, so checking twice in a row does not skip anything.

next() returns the next element of type E and advances the iterator. Once the iterator is exhausted, it throws NoSuchElementException rather than returning null to signal the end. A typical loop uses while (it.hasNext()) and calls it.next() inside the body.

remove() is optional and takes no arguments. If supported, it removes the last element returned by that same iterator from the underlying collection. It is allowed only once per successful next() call. Calling it before the first next(), or attempting a second removal without another successful next(), causes IllegalStateException. If removal is unsupported, remove() throws UnsupportedOperationException; the default implementation throws that exception without changing anything.

During iteration, do not modify the underlying collection except through that iterator's remove(), unless the implementation specifies a concurrent modification policy. Otherwise, iterator behavior is unspecified. The general contract also leaves remove() behavior unspecified after forEachRemaining().

Examples

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class Main {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>(List.of("A", "B"));
        Iterator<String> it = items.iterator();

        System.out.println(it.hasNext());
        System.out.println(it.hasNext());
        System.out.println(it.next());
        it.remove();
        try {
            it.remove();
        } catch (IllegalStateException e) {
            System.out.println("IllegalStateException");
        }
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        System.out.println(it.hasNext());
        try {
            it.next();
        } catch (NoSuchElementException e) {
            System.out.println("NoSuchElementException");
        }
        System.out.println(items);

        Iterator<String> readOnly = List.of("A").iterator();
        readOnly.next();
        try {
            readOnly.remove();
        } catch (UnsupportedOperationException e) {
            System.out.println("UnsupportedOperationException");
        }
    }
}

Result

true
true
A
IllegalStateException
B
false
NoSuchElementException
[B]
UnsupportedOperationException

Both `hasNext()` calls print `true`, and the first `next()` still returns `A`. The `ArrayList` iterator removes `A`, rejects the repeated removal, and is exhausted after returning `B`. Only `B` remains in the list. The iterator of the unmodifiable `List.of(...)` list rejects removal even after a successful `next()`.

Related lessons

  • Java · Lesson 24 · Intermediate · Version: 2

Sources