ListIterator Bidirectional List Traversal

Walk an ArrayList forward with next() and backward with previous() from the same cursor, and replace elements in place via set() during iteration.

JavaData Integrity

Code

snippet
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class BidirectionalWalk {

    public static void main(String[] args) {
        List<String> stages = new ArrayList<>(List.of("build", "test", "package", "sign"));

        // listIterator(size()) 把光标放到末尾:先用 previous 倒着走一遍
        ListIterator<String> back = stages.listIterator(stages.size());
        while (back.hasPrevious()) {
            System.out.println("reverse: " + back.previousIndex() + " -> " + back.previous());
        }

        // 正向遍历途中用 set() 原位替换元素,不需要额外索引变量
        ListIterator<String> forward = stages.listIterator();
        while (forward.hasNext()) {
            String stage = forward.next();
            if (stage.equals("test")) {
                forward.set("test (parallel)");
            }
        }
        System.out.println(stages);
    }
}

How it works

The working surface is the class BidirectionalWalk and the function main — everything else is wiring.

The file repeats itself only inside while (back.hasPrevious()).

Points of care

  • The only prerequisite is the language toolchain itself.

Applying it

Entry signature: public static void main(String[] args)

The demo output is labeled (reverse:), so every printed line maps back to its originating operation.

Statements that matter

List<String> stages = new ArrayList<>(List.of("build", "test", "package", "sign"));
ListIterator<String> back = stages.listIterator(stages.size());
ListIterator<String> forward = stages.listIterator();

Interactive Tools for This Topic

FAQ

What does ListIterator Bidirectional List Traversal print when run?
Run it as a complete program — the output lines carry labels such as `reverse:`.