Handling ConcurrentModificationException with ArrayList in Java 11
I'm building a feature where I'm facing a `ConcurrentModificationException` while iterating over an `ArrayList` in Java 11..... My code looks like this: ```java import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); for (String fruit : list) { if (fruit.equals("Banana")) { list.remove(fruit); } } } } ``` When I run this code, I get the following error: ``` Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1021) at java.util.ArrayList$Itr.next(ArrayList.java:901) ``` I understand that removing items from a list while iterating over it can lead to this exception, but I thought this was a valid way to modify the list. I've tried using an `Iterator` instead, as follows: ```java Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.equals("Banana")) { iterator.remove(); } } ``` However, this still throws a `ConcurrentModificationException`. I've also checked if there might be other threads modifying the list, but there aren't any in this simple example. What am I missing here? Is there a best practice for safely removing items from a list during iteration in Java 11? Any insights would be greatly appreciated! Has anyone dealt with something similar?