Junior — Middle
What happens if you delete an element from a collection inside a foreach loop?
sobes.tech AI
Answer from AI
If you try to remove an element from a collection inside a foreach (enhanced for loop) in Java, a ConcurrentModificationException will occur. This happens because foreach uses an internal iterator that tracks changes to the collection, and removing elements directly disrupts its state.
To safely remove elements during iteration, you should use an explicit iterator and its remove() method:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (item.equals("b")) {
iterator.remove(); // safe removal
}
}