From the API:
The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
This means that if you want to modify the collection while iterating over it you must use the iterator.remove() method. Rather than using a for each loop, try something like this:
Collection items = ...
Iterator itr = items.iterator();
while(itr.hasNext()) {
Object o = itr.next();
boolean condition = ...
if(condition) {
itr.remove();
}
}
Or if you can (and would prefer to) make the modification after the iteration is complete you can do something like this:
Collection items = ...
Collection itemsToRemove = ...
for (Object item : items) {
boolean condition = ...
if (condition) {
itemsToRemove.add(item);
}
}
items.removeAll(itemsToRemove);
If your collection is of type List, then you can get a ListIterator by invoking listIterator(). A ListIterator augments Iterator by adding methods which allow traversing the list bidirectionally and allows modifying the collection by adding and removing items, or replacing the current item.