Skip to main content



      Home
Home » Language IDEs » Java Development Tools (JDT) » Java's for each loop
Java's for each loop [message #1858692] Sun, 16 April 2023 17:49 Go to next message
Eclipse UserFriend
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?
Re: Java's for each loop [message #1858697 is a reply to message #1858692] Mon, 17 April 2023 00:08 Go to previous message
Eclipse UserFriend
Hi,

Works fine here...

index.php/fa/43118/0/

Previous Topic:Easy question
Next Topic:Issue with ecj compiler and Java 11
Goto Forum:
  


Current Time: Tue Jul 15 19:29:20 EDT 2025

Powered by FUDForum. Page generated in 0.03315 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top