Can You Safely Remove Items Inside a Java foreach Loop? Why It Fails and How to Fix It
This article explores whether elements can be deleted or modified within Java's foreach loop, compares it with traditional for loops, explains the iterator behavior that triggers ConcurrentModificationException, and demonstrates the correct use of iterator.remove() and object property updates.
Overview
The discussion focuses on whether elements in a Java List can be removed or modified while iterating with a foreach loop, and compares this approach with the classic for loop.
(1) Traversing Elements
Two examples show how an array and an ArrayList are traversed. The compiled bytecode reveals that array traversal uses a traditional for loop, while collection traversal uses an Iterator.
String[] array = {"1", "2", "3"};
for (String i : array) {
System.out.println(i);
}
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
for (String i : list) {
System.out.println(i);
}(2) Deleting Elements
Using a classic for loop works because the loop index is managed manually.
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
for (int i = 0; i < list.size(); i++) {
list.remove("222");
}The list after removal contains [111, 333].
Using a foreach loop throws ConcurrentModificationException because the underlying iterator detects that the list’s modCount changed without using the iterator’s own remove() method.
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
for (String i : list) {
list.remove("222");
}Result: java.util.ConcurrentModificationException.
Correct approach: use the iterator’s remove() method.
ArrayList<String> list = new ArrayList<>();
list.add("111");
list.add("222");
list.add("333");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String next = it.next();
if (next.equals("222")) {
it.remove();
}
}After execution the list becomes [111, 333].
(3) Modifying Elements
Using a classic for loop can replace each element with list.set(i, "444"), resulting in [444, 444, 444].
for (int i = 0; i < list.size(); i++) {
list.set(i, "444");
}Using a foreach loop does not modify the list because the loop variable holds a copy of the reference; assigning a new value to it does not affect the underlying collection.
for (String i : list) {
i = "444"; // no effect on the list
}(4) Modifying Object Properties Inside foreach
Although the collection element itself cannot be replaced, its internal state can be changed. A Student class with age and name fields demonstrates this.
public class Student {
private int age;
private String name;
// getters and setters omitted for brevity
public Student() {}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
}Iterating with foreach and calling stu.setName("jingtian") updates the name of each student object, and the change is reflected when the objects are printed.
for (Student stu : studentList) {
stu.setName("jingtian");
}Summary
Both for and foreach can traverse arrays and collections; for may be more efficient in complex loops. foreach cannot directly delete or replace collection elements; for can.
Both loops can modify the properties of objects contained in the collection.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
