Java
remove
Learn safe removal with Iterator.remove.
The iterator.remove() method
To remove an element during traversal use iterator.remove(). This method deletes the element most recently returned by next(). Calling remove on the same Iterator without a prior next throws IllegalStateException.
Modifying a list inside a for-each loop is forbidden; it throws ConcurrentModificationException. For conditional removal, the Iterator's remove method is the safe path.
The conditional removal pattern
The classic pattern for conditional removal is while (it.hasNext()) { String s = it.next(); if (condition) it.remove(); }. After each removal the Iterator cursor stays in place; the next next call returns the new element.
This pattern is ideal for cleaning a list of elements that match a condition. For example s.length() > 5 drops long names, s.isEmpty() drops empty strings. remove can be called at most once per next.
Exercise Remove long names with an Iterator
Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alexander", "Alex". Get an Iterator with Iterator<String> it = names.iterator();. In a while (it.hasNext()) loop call String s = it.next();; if s.length() > 5 call it.remove();. After the loop print the remaining count with System.out.println(names.size());.
Show example solution
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alexander");
names.add("Alex");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.length() > 5) it.remove();
}
System.out.println(names.size());
}
}
Test yourself
-
Complete the remove call
String s = it.next();
if (s.isEmpty()) {
it.____();
}
Show answer
String s = it.next();
if (s.isEmpty()) {
it.remove();
}
-
When does it.remove() throw IllegalStateException?
- Before next is called
- When hasNext returns false
- When remove is called twice
- When the list is empty
Show answer
Before next is called — Calling remove before next throws IllegalStateException.
-
Match the remove behaviors
- remove()
- Deletes last read
- IllegalStateException
- remove without next
- ConcurrentModificationException
- Removal in for-each
- next()
- Required before remove
Next lesson: ListIterator