Pentium10 Pentium10 - 1 year ago 78
Java Question

When removing inside foreach, do we need to step back

Take this Java code:

for (ContactsReduced curContact : allcontacts) {

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download