Adding Elements with add
You'll learn how ListIterator's add() method inserts elements at the iterator's current cursor position.
While Iterator only lets you remove elements during traversal, ListIterator goes further—it allows you to insert new elements on the fly. The add(E element) method places a new element into the list at the iterator's current position.
How add Works
Think of the ListIterator cursor as sitting between elements, like a text editor cursor between characters. When you call add(E element), the new element is inserted immediately before the implicit cursor position—essentially right before whatever element next() would return.
After insertion, the cursor moves forward, so the newly added element is now behind the cursor. This means:
- A subsequent
next()won't return the element you just added - A subsequent
previous()would return it
Here's the key behavior pattern:
List<String> list = new ArrayList<>(List.of("A", "C"));
ListIterator<String> it = list.listIterator();
it.next(); // cursor moves past "A"
it.add("B"); // inserts "B" between "A" and "C"
// List is now ["A", "B", "C"]
// cursor is between "B" and "C"
it.next(); // returns "C", not "B"
Side Effects of add
After calling add(), the iterator's state resets slightly: you cannot immediately call remove() or set() because those operate on the last element returned by next() or previous(), and add() didn't return anything.
Key Takeaway: ListIterator.add(E element) inserts elements at the cursor position, immediately before what next() would return, and moves the cursor forward past the new element.