How to remove an element from an ArrayList during iteration?

This question is usually framed as a "spot the issue" task, for example:
for (String item : arrayList)
if (item.length() > 2)
arrayList.remove(item);

The catch here is that the ArrayList iterator used in this type of for loop is fail-fast, meaning it does not support concurrent modification during iteration. Concurrent modification can occur even within a single thread, as demonstrated in this example. The next iteration step after removing an element will throw a ConcurrentModificationException.

No exception, but unexpected results can occur if using a regular for loop – each removal will shift the indexing of elements.

The only way to remove an element from a collection while iterating without receiving a ConcurrentModificationException or undefined behavior is to use the remove() method of the same iterator instance. A ListIterator would be helpful if index manipulation is also required within the loop body.

Some collections, such as CopyOnWriteArrayList and ConcurrentHashMap, are adapted for multi-threaded environments and have fail-safe iterators.