Video in progress
What happens if you remove an element from a list inside a for-each loop?
Most of the time a ConcurrentModificationException is thrown: for-each uses a hidden iterator, and the list was modified behind its back. The right way is iterator.remove() or list.removeIf(...).
📖 Answer
List<String> names = new ArrayList<>(List.of("Ali", "Vali", "Gani"));
for (String n : names) {
if (n.startsWith("V")) {
names.remove(n); // ConcurrentModificationException
}
}
ArrayList keeps a modCount counter inside. Every add/remove increments it. An iterator remembers the value when it is created and checks it on every next(). If the numbers differ, you get the exception.
The interesting part: if the removed element is the second to last one, the exception may not be thrown at all, and the loop simply ends. So don't rely on this error showing up.
The correct way:
names.removeIf(n -> n.startsWith("V"));
// or the old-school way
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("V")) it.remove();
}
Sign up to mark studied questions and save your progress.