How to remove elements from a collection in a loop without ConcurrentModificationException in Java?
Hello everyone! I'm a beginner Java developer and I've encountered a very strange error. I'm writing a simple program: there is a list of strings, and I want to remove all elements that start with the letter "A". It seems logical, but when I run it, I get a ConcurrentModificationException.
Here is my code:
```java
List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Avocado", "Cherry"));
for (String fruit : list) {
if (fruit.startsWith("A")) {
list.remove(fruit);
}
}
```
The error occurs on the iteration after the removal. I've read that you cannot modify a collection during a for-each loop, but how do I correctly remove elements? I need to modify the original list, not create a new one.
Please tell me how to do this correctly? What are the ways?