Pentium10 Pentium10 - 4 months ago 11
Java Question

When removing inside foreach, do we need to step back

Take this Java code:

for (ContactsReduced curContact : allcontacts) {
..........
allcontacts.remove(curContact);
}


I do based on a condition a remove, will the foreach miss the next item in order, and do we need to step back(somehow)?

Answer

That code will break with most collections - other than a few collections such as those in java.util.concurrent, modifying a collection while iterating over it isn't supported.

A few options:

  • Obtain and use an iterator explicitly (call iterator() on the collection) instead of an enhanced for loop, and call iterator.remove() to remove an item
  • Use a plain for loop, either moving forwards and stepping back after the removal or moving backwards from the end
  • Maintain a separate list of items to remove, and then remove them after iterating