IllegalStateException from remove()
You'll learn why calling remove() at the wrong time during iteration throws an exception.
The Problem with Improper remove() Calls
You've learned that the remove() method on an Iterator lets you safely delete elements while iterating. However, remove() has strict rules about when you can call it. If you break these rules, Java throws an IllegalStateException.
The Two Golden Rules
Rule 1: You must call next() before calling remove()
The remove() method deletes the element that was just returned by next(). If you haven't called next() yet, there's nothing to remove, so Java throws an exception.
Rule 2: You can only call remove() once per next() call
After calling remove(), you must call next() again before you can remove another element. Calling remove() twice in a row attempts to delete an element that's already gone.
Example Violations
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> it = list.iterator();
// WRONG: remove() before any next() call
it.remove(); // ❌ IllegalStateException!
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
Iterator<String> it = list.iterator();
String first = it.next(); // "A"
it.remove(); // ✅ OK - removes "A"
it.remove(); // ❌ IllegalStateException! (no next() in between)
The Correct Pattern
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String element = it.next();
if (shouldRemove(element)) {
it.remove(); // ✅ OK - called once after next()
}
}
Key Takeaway: Always call next() before remove(), and only call remove() once per next() call—otherwise you'll get an IllegalStateException.