Simberon Design Minute
 

Changing Collections while Looping

One common mistake developers make when using a collections library is to modify a collection while iterating over it. For sequenceable collections, removing elements before the current iteration point will cause problems and for hashed collections like Sets or Dictionaries, any add or remove to the collection will cause problems. Some environments try to fix the problem by providing special operations to the iterator to allow you to add and remove elements. This solution doesn't work in all cases such as adding and removing elements at other spots in the collection than the current spot. The best thing to do is usually to iterate over a copy of the collection and make the changes to the original. This allows you to have a fixed collection of objects to loop over that doesn't change during the loop.

Download