Sub topic 6
Removing Elements Safely While Iterating
In the last chapter you looped over a list with for-each. Reading is safe. Removing elements while you loop needs more care. This chapter shows the error you get if you remove elements the wrong way, and two safe ways to do it.
The Problem: ConcurrentModificationException
An exception is an error object that Java throws when something goes wrong at run time. ConcurrentModificationException is an exception that a collection throws when it changes while a loop is still walking through it.
A for-each loop uses a hidden iterator behind the scenes. An iterator is an object that walks through a collection one element at a time. The iterator remembers how the list looked when the loop started. If you call list.remove(...) directly inside the loop, the list changes without the iterator knowing. On its next step, the iterator notices the change and throws the exception.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class BrokenRemoveDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "fig", "banana", "kiwi"));
try {
for (String w : words) {
if (w.length() < 4) {
words.remove(w); // changes the list behind the loop's back
}
}
} catch (ConcurrentModificationException e) {
System.out.println("Caught ConcurrentModificationException");
}
System.out.println(words); // [apple, banana, kiwi]
}
}The word "fig" was removed, but the loop crashed straight after. In real code, this crash would stop your program.
Safe Way 1: Iterator.remove
If you create the iterator yourself, you can ask it to do the removal. Then the iterator knows about the change and stays in step with the list.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorRemoveDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "fig", "banana", "kiwi"));
Iterator<String> it = words.iterator();
while (it.hasNext()) {
String w = it.next();
if (w.length() < 4) {
it.remove(); // removes the element that next() just returned
}
}
System.out.println(words); // [apple, banana, kiwi]
}
}Call it.remove() only after calling it.next(), and at most once for each next() call. If you break this rule, Java throws IllegalStateException.
Safe Way 2: removeIf
removeIf is a method that removes every element matching a test. You pass the test as a lambda, which is a short function written inline, such as w -> w.startsWith("k"). The collection runs the loop for you.
import java.util.ArrayList;
import java.util.List;
public class RemoveIfDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("apple", "kiwi", "banana", "fig"));
words.removeIf(w -> w.startsWith("k"));
System.out.println(words); // [apple, banana, fig]
}
}For simple rules, removeIf is usually the clearest choice.
Summary
| Approach | Safe? | When to use it |
|---|---|---|
| `list.remove` inside for-each | No | Never |
| `Iterator.remove` | Yes | When the rule is complex or you need to do more work on each element |
| `removeIf` | Yes | When the rule fits in one short test |
Exercise
You have a List<Integer> called scores. Write one line that removes every score below 50 without causing ConcurrentModificationException.
Show answer
scores.removeIf(s -> s < 50); This works because removeIf runs the loop itself and removes each matching element safely.
Exercise
Inside a while loop with an Iterator named it, a student calls it.remove() twice in a row after a single it.next(). What happens?
Show answer
The second call throws IllegalStateException. You can call remove only once for each call to next.