Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.ListIterator: practical reference

util.ListIterator: practical reference: ListIterator<E> has a cursor between list elements and can traverse both directions while editing the current position safely.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.ListIterator

ListIterator has a cursor between list elements and can traverse both directions while editing the current position safely.

Use it for a one-pass list rewrite that needs next, previous, add, set, or remove without separate index arithmetic.

set and remove require a preceding next or previous and throw IllegalStateException after add or a repeated remove; fail-fast is no concurrency guarantee.

At the beginning previousIndex is -1 and at the end nextIndex is size; add inserts before next and after the element returned by previous.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        java.util.ListIterator<String> iterator = java.util.List.of("a", "b").listIterator(2);
        System.out.println(iterator.previous());
        System.out.println(iterator.previousIndex());
    }
}

Result

b
0

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources