Removing objects from a collection in a loop without ConcurrentModificationException
Hi everyone! I'm writing a small Java application for managing a task list. I have an ArrayList, where Task is a simple POJO with a boolean field isCompleted. I need to remove all completed tasks from the list. I wrote this code:
```java
List tasks = new ArrayList<>();
// ... adding tasks ...
for (Task task : tasks) {
if (task.isCompleted()) {
tasks.remove(task);
}
}
```
But when I run it, I get a `ConcurrentModificationException`. I've read that this is related to modifying the collection during iteration, but I don't understand how to do it correctly. I tried using a regular for loop with an index — sometimes it works, sometimes it throws an IndexOutOfBoundsException because the indices shift after removal. Please advise how to properly remove elements