Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » Java's for each loop
Java's for each loop [message #1858692] Sun, 16 April 2023 21:49 Go to next message
bretny relly is currently offline bretny rellyFriend
Messages: 14
Registered: March 2023
Junior Member
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 04:08 Go to previous message
Eitan Rosenberg is currently offline Eitan RosenbergFriend
Messages: 149
Registered: October 2018
Senior Member
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: Sat Jan 25 17:22:20 GMT 2025

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

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

Back to the top