Question
How can I remove an object from an ArrayList while iterating over it using a for-each loop in Java?
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
for(String item : list) {
if(item.equals("B")) {
list.remove(item); // This will cause ConcurrentModificationException
}
}
Answer
Removing elements from a Java ArrayList while iterating over it using a for-each loop is problematic because it can lead to a ConcurrentModificationException. Instead, consider using an Iterator or filter the list based on certain conditions before deletion.
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
String item = iterator.next();
if(item.equals("B")) {
iterator.remove(); // Safely removes the current element
}
}
Causes
- Using for-each loop which modifies the ArrayList directly leads to ConcurrentModificationException.
- The iterator does not recognize the changes made to the collection during traversal.
Solutions
- Use an explicit Iterator to safely remove elements during iteration.
- Create a separate list to collect elements to be removed and delete them after the iteration.
- Utilize Java 8 Streams for filtering elements without modifying the original list.
Common Mistakes
Mistake: Attempting to remove an object from the ArrayList with a for-each loop directly.
Solution: Switch to using an explicit Iterator or store them for removal after the loop.
Mistake: Confusion between removing elements during iteration which causes exceptions.
Solution: Understand the flow of the for-each loop and the underlying collection modification rules.
Helpers
- Java ArrayList remove object
- for-each loop remove element
- ConcurrentModificationException
- Java Iterator remove
- Java Collections best practices