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 theArrayList
. - 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
Parameter | Description |
---|---|
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()
, andremove()
methods of the iterator to avoidConcurrentModificationException
. - 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
Aspect | Details |
---|---|
Method Purpose | List traversal (forward/backward), safe in-place modification |
Syntax | list.listIterator() or list.listIterator(int startIndex) |
Returns | ListIterator object |
Cursor Direction | Bidirectional |
Key Methods | hasNext() , next() , hasPrevious() , previous() , add() , set() , remove() |
Throws Exception | IndexOutOfBoundsException for bad start index |
Typical Use Cases | Iterating 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.