The ArrayList.listIterator() method returns a fail-fast java.util.ListIterator<E> that can traverse the list in both forward and reverse directions, inspect cursor indices, and safely insert, replace, or remove elements during iteration.
Safe In-Loop Mutation: Calling ArrayList.add() or ArrayList.remove() directly on the list inside a for-each loop throws a ConcurrentModificationException. Using ListIterator.add(), ListIterator.set(), and ListIterator.remove() updates the list safely while keeping the iterator synchronized.
Declared in java.util.ArrayList<E> (requires import java.util.ListIterator;):
// 1. Returns a list iterator starting at index 0
public ListIterator<E> listIterator()
// 2. Returns a list iterator starting at the specified position (0 <= index <= size())
public ListIterator<E> listIterator(int index)
| Overload Signature | Initial Cursor Position | First Call Behavior |
|---|---|---|
listIterator() |
Before index 0 |
next() returns get(0); hasPrevious() is false. |
listIterator(int index) |
Before index |
next() returns get(index); previous() returns get(index - 1). |
Using hasNext() / next() to walk from the beginning to the end of marks, and then hasPrevious() / previous() to walk back to the start:
import java.util.ArrayList;
import java.util.ListIterator;
ArrayList<Integer> marks = new ArrayList<>(Arrays.asList(51, 52, 53, 54));
System.out.println(marks); // [51, 52, 53, 54]
ListIterator<Integer> my_iterator = marks.listIterator();
while (my_iterator.hasNext()) {
System.out.print(my_iterator.next() + " ");
}
System.out.println("\nForward traversing is over.");
while (my_iterator.hasPrevious()) {
System.out.print(my_iterator.previous() + " ");
}Terminal Output:
[51, 52, 53, 54]
51 52 53 54
Forward traversing is over.
54 53 52 51
You do not need to loop forward first just to iterate backward! Passing steps.size() to steps.listIterator(steps.size()) places the cursor immediately after the last element so previous() walks from the tail to the head:
ArrayList<String> steps = new ArrayList<>(Arrays.asList("First", "Second", "Third"));
// Start cursor directly at steps.size() (3) to walk backward immediately!
ListIterator<String> rev = steps.listIterator(steps.size());
while (rev.hasPrevious()) {
System.out.println("Index " + rev.previousIndex() + ": " + rev.previous());
}Terminal Output:
Index 2: Third
Index 1: Second
Index 0: First
ListIterator provides three mutation methods that modify the underlying ArrayList without invalidating the iterator: it.remove() deletes the last element returned by next()/previous(), it.set(E) replaces it, and it.add(E) inserts a new element immediately before the implicit cursor:
ArrayList<String> langs = new ArrayList<>(Arrays.asList("java", "bad", "python"));
ListIterator<String> it = langs.listIterator();
while (it.hasNext()) {
String val = it.next();
if ("bad".equals(val)) {
it.remove(); // Safe removal during iteration
} else {
it.set(val.toUpperCase()); // Safe replacement of last returned element
if ("java".equals(val)) it.add("PHP"); // Safe insertion right after JAVA
}
}
System.out.println("Mutated list: " + langs);Terminal Output:
Mutated list: [JAVA, PHP, PYTHON]
A ListIterator cursor always sits between two elements. nextIndex() returns the index of the element that would be returned by next() (or size() if at the end), and previousIndex() returns the index of the element that would be returned by previous() (or -1 if at the start):
ArrayList<String> items = new ArrayList<>(Arrays.asList("A", "B"));
ListIterator<String> it = items.listIterator(1); // Cursor sits between "A" (0) and "B" (1)
System.out.println("previousIndex(): " + it.previousIndex()); // 0
System.out.println("nextIndex(): " + it.nextIndex()); // 1Terminal Output:
previousIndex(): 0
nextIndex(): 1
Choosing the right traversal mechanism for ArrayList:
| Feature | ListIterator<E> |
Iterator<E> |
Enhanced for-each |
|---|---|---|---|
| Reverse Traversal | Yes (previous()) |
No (Forward only) | No (Forward only) |
In-Loop set() / add() |
Yes | No (Only remove()) |
No (Throws CME) |
| Cursor Index Lookup | Yes (nextIndex()) |
No | No |
Removing invalid negative entries while incrementing valid entries in a single pass with ListIterator:
public class PriceAdjuster {
public static void main(String[] args) {
ArrayList<Integer> prices = new ArrayList<>(Arrays.asList(100, -5, 250));
ListIterator<Integer> it = prices.listIterator();
while (it.hasNext()) {
int p = it.next();
if (p < 0) it.remove();
else it.set(p + 10);
}
System.out.println("Adjusted prices: " + prices);
}
}Terminal Output:
Adjusted prices: [110, 260]
Running one ListIterator forward from 0 and a second backward from size() until their cursor indices meet:
ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(10, 20, 10));
ListIterator<Integer> fwd = nums.listIterator(), rev = nums.listIterator(nums.size());
boolean sym = fwd.next().equals(rev.previous());
System.out.println("Ends match? " + sym);Terminal Output:
Ends match? true
If you call marks.add(99) directly on the ArrayList while a ListIterator is active, the next call to my_iterator.next() throws a ConcurrentModificationException! Always invoke my_iterator.add(99) on the iterator itself.
it.remove() and it.set(val) operate on the last element returned by the most recent next() or previous() call. Calling them before any movement—or immediately after it.add()—throws an IllegalStateException.
Compile and run this verification class in any Java environment:
public class ArrayListListIteratorFullDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "C"));
ListIterator<String> it = list.listIterator(1);
it.add("B"); // Inserts "B" at index 1
if (list.equals(Arrays.asList("A", "B", "C"))) {
System.out.println("Check 1 Passed: listIterator(1).add('B') produced [A, B, C].");
}
if (it.previous().equals("B")) {
System.out.println("Check 2 Passed: previous() returned newly added element 'B'.");
}
System.out.println("All ArrayList.listIterator() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: listIterator(1).add('B') produced [A, B, C].
Check 2 Passed: previous() returned newly added element 'B'.
All ArrayList.listIterator() verification checks passed!
Alternating it.next() and it.previous() returns the exact same element repeatedly because the cursor steps forward over the element and then immediately steps back over the same element.
No. it.add(e) inserts the new element before the implicit cursor, so a subsequent call to it.next() is unaffected, while a subsequent call to it.previous() returns the newly added element.
If index < 0 or index > size(). Note that index == size() is valid and positions the cursor at the end of the list.
Yes. Calling list.subList(from, to).listIterator() returns a bidirectional iterator scoped strictly to that range.
ArrayList.listIterator(list.size()).ArrayList.ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.