Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList listIterator() Method

Posted on July 23, 2025July 23, 2025 By Admin No Comments on Java ArrayList listIterator() Method

The listIterator() method is a powerful feature of Java’s ArrayList class, enabling you to traverse an ArrayList both forwards and backwards. Unlike the basic iterator(), listIterator() also allows modification (addition, update, removal) of elements during iteration and offers more advanced cursor control. This makes it essential for flexible list manipulation scenarios.

What Is the listIterator() Method in ArrayList?

  • The listIterator() method returns a ListIterator object for the ArrayList.
  • ListIterator allows you to move forward and backward through the list, access indices, and safely modify the list’s elements during iteration.
  • It comes in two main forms: starting at the beginning or at a specified index.

Syntax

public ListIterator<E> listIterator()
public ListIterator<E> listIterator(int index)

Where:

  • E is the type of elements in the list.
  • index is the position at which the iterator starts.

Parameters

ParameterDescription
index(Optional) The index at which the cursor starts (0 ≤ index ≤ size())
  • If no index is given, iteration starts at the beginning (index 0).

Return Value

  • Returns a ListIterator over the elements in the list (in sequence).
  • With listIterator(index), the iterator starts at the given position.

Exceptions

  • IndexOutOfBoundsException: Thrown if the specified index is out of range (index less than 0 or greater than size of the list).
  • No other checked exceptions for creation.

How Does listIterator() Work Internally?

  • The ListIterator maintains a cursor between elements, allowing bidirectional traversal.
  • Key methods you can use:
    • hasNext(), next(): Move forward.
    • hasPrevious(), previous(): Move backward.
    • nextIndex(), previousIndex(): Query current cursor position.
    • add(E e): Insert new elements.
    • set(E e): Update current element.
    • remove(): Remove current element safely during iteration.

Examples of the listIterator() Method

1. Basic Forward & Backward Traversal

import java.util.ArrayList;
import java.util.ListIterator;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        ListIterator<String> it = fruits.listIterator();

        System.out.println("Forward:");
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        System.out.println("Backward:");
        while (it.hasPrevious()) {
            System.out.println(it.previous());
        }
    }
}

Output:

Forward:
Apple
Banana
Orange
Backward:
Orange
Banana
Apple

2. Starting Iteration from a Specific Index

import java.util.ArrayList;
import java.util.ListIterator;

public class Example {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        // Start from index 1
        ListIterator<Integer> it = numbers.listIterator(1);

        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Output:

20
30

3. Modifying Elements While Iterating

import java.util.ArrayList;
import java.util.ListIterator;

public class ModifyDemo {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        ListIterator<String> it = names.listIterator();
        while (it.hasNext()) {
            String name = it.next();
            if (name.equals("Bob")) {
                it.set("David"); // Change "Bob" to "David"
            }
        }
        System.out.println(names); // Output: [Alice, David, Charlie]
    }
}

4. Adding and Removing Elements During Iteration

import java.util.ArrayList;
import java.util.ListIterator;

public class AddRemoveDemo {
    public static void main(String[] args) {
        ArrayList<String> items = new ArrayList<>();
        items.add("Book");
        items.add("Pen");

        ListIterator<String> it = items.listIterator();
        it.next(); // "Book"
        it.add("Notebook"); // Insert after "Book"
        it.next(); // "Pen"
        it.remove(); // Remove "Pen"

        System.out.println(items); // Output: [Book, Notebook]
    }
}

Important Notes

  • Bidirectional Navigation: ListIterator can move both forward and backward, unlike Iterator.
  • Safe Modifications: Use add(), set(), and remove() methods of the iterator to avoid ConcurrentModificationException.
  • Current Cursor: The cursor position is always between elements (not on elements).
  • Starting Position: Specifying listIterator(index) is useful for partial traversals or edits.
  • Read and Write: Can be used for searching, updating, inserting, and deleting elements in place.

Summary

AspectDetails
Method PurposeList traversal (forward/backward), safe in-place modification
Syntaxlist.listIterator() or list.listIterator(int startIndex)
ReturnsListIterator object
Cursor DirectionBidirectional
Key MethodshasNext(), next(), hasPrevious(), previous(), add(), set(), remove()
Throws ExceptionIndexOutOfBoundsException for bad start index
Typical Use CasesIterating in both directions, modifying existing elements during iteration

Typical Use Cases

  • Editing a list during iteration (update, insert, or remove elements).
  • Traversing lists backwards and forwards for complex processing.
  • Building new lists from old ones during multi-stage transformations.
  • Implementing undo/redo or rolling back in data structures.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList lastIndexOf() Method
Next Post: Java ArrayList remove() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme