Course contentsShow
← Java
Lesson 1288 of 2,87029. Iterators and IterableFree lesson

The remove Method in ListIterator

Removing the last returned element with remove() and understanding the state requirements for safe removal.

The remove Method in ListIterator

You'll learn how to safely remove the last returned element using remove() in a ListIterator and the state requirements for doing so.

Understanding ListIterator's remove

Just like the basic Iterator, ListIterator provides a remove() method to delete elements during iteration. However, it has strict rules about when you can call it.

The remove() method removes the last element returned by either next() or previous(). You cannot call remove() unless you've just called one of these methods. If you try to call remove() twice in a row, or call it before calling next() or previous(), you'll get an IllegalStateException.

Think of it like a safety mechanism: the iterator must "know" which element you're referring to. Only next() or previous() establishes that reference.

State Requirements for Safe Removal

List<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie", "Diana"));
ListIterator<String> iter = names.listIterator();

iter.next();        // Returns "Alice"
iter.remove();      // OK: removes "Alice"

// iter.remove();   // IllegalStateException: no element to remove

iter.next();        // Returns "Bob"
iter.previous();    // Returns "Bob" (back to it)
iter.remove();      // OK: removes "Bob" (last returned)

iter.next();        // Returns "Charlie"
iter.add("Eve");    // Adds "Eve" after "Charlie"
// iter.remove();   // IllegalStateException: add() clears the "last returned" state

Note that calling add() or set() also clears the "last returned" state, making subsequent remove() calls invalid until you call next() or previous() again.

Key Takeaway:
ListIterator.remove() deletes the last element returned by next() or previous(), and can only be called once per navigation call—calling add(), set(), or remove() again without another next()/previous() throws IllegalStateException.