Java's for each loop [message #1858692] |
Sun, 16 April 2023 17:49  |
Eclipse User |
|
|
|
What is causing my for-each loop to throw a "ConcurrentModificationException" error when I try to modify the collection within the loop? How can I modify the collection safely?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
int number = iterator.next();
if (number % 2 == 0) {
iterator.remove();
}
}
System.out.println(numbers);
}
}
In general, it's advisable to avoid altering a collection while it's being iterated over. If changes are required, consider utilising a synchronised collection or another thread-safe collection to avoid concurrent modification, as described in this article.
So what happens if I try to change the collection within the loop? How can I safely modify the collection?
|
|
|
|
Powered by
FUDForum. Page generated in 0.03315 seconds