Why Deleting Elements from a Java List Inside a For Loop Is Unsafe and How to Do It Correctly
This article explains why deleting elements from a Java List while iterating with a for loop is unsafe, demonstrates the correct approach using an Iterator or removeIf, and analyzes common pitfalls of both classic for and enhanced foreach loops.
Conclusion: never delete List elements while iterating with a for loop, regardless of the scenario, because it leads to logical bugs and runtime exceptions.
The Alibaba development manual also explicitly forbids using foreach to add or remove List elements.
Correct ways to remove elements include using an Iterator :
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
// delete element
iterator.remove();
}Or, with Java 8+ lambda syntax:
list.removeIf(s -> s.contains("a"));
If you only want to know why the for-loop deletion is prohibited, you can stop reading now; otherwise, continue for the detailed reasons.
Example
Scenario: a List<String> with N elements, remove all elements containing the character "a".
List<String> list = new ArrayList<>(4);
list.add("a");
list.add("ab");
list.add("abc");
list.add("abcd");Correct Solution
public static void main(String[] args) {
List<String> list = new ArrayList<>(4);
list.add("a");
list.add("ab");
list.add("abc");
list.add("abcd");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
if (iterator.next().contains("a")) {
// delete element
iterator.remove();
}
}
System.out.println(list);
}Output:
[]Wrong Answer 1: Classic for-loop
public static void main(String[] args) {
List<String> list = new ArrayList<>(4);
list.add("a");
list.add("ab");
list.add("abc");
list.add("abcd");
for (int i = 0; i < list.size(); i++) {
if (list.get(i).contains("a")) {
list.remove(i);
}
}
System.out.println(list);
}Output:
[ab, abcd]Analysis: Deleting while iterating with an index causes the subsequent elements to shift, so the next element is skipped, leading to incorrect results.
Although the code runs without error, it is a bug because the logic misses elements after each deletion, making it unreliable in production.
Wrong Answer 2: Enhanced for-loop (foreach)
public static void main(String[] args) {
List<String> list = new ArrayList<>(4);
list.add("a");
list.add("ab");
list.add("abc");
list.add("abcd");
for (String str : list) {
if (str.contains("a")) {
list.remove(str);
}
}
System.out.println(list);
}Runtime error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at ...Explanation: The foreach loop does not support structural modifications (add/remove) of the collection during iteration, though it allows element modification.
Conclusion: Use an Iterator or Java 8+ removeIf for safe removal; avoid modifying a List inside any form of for-loop.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.