0

I heard that it is not good style to change a list which you are iterating over within the iteration.

Example (pseudo code):

for (int i = 0; i < someList.length(); i++) {
  someList.getAt(i).doSomething();
}

Why is that? Could there be any side effects?

Blender
  • 275,078
  • 51
  • 420
  • 480
Michael Kohler
  • 742
  • 10
  • 22

2 Answers2

0

Make a copy. Change that, iterate around the original.

Otherwise the iterator won't know about changes made. More here:

Modifying list while iterating

Community
  • 1
  • 1
Paul Collingwood
  • 9,066
  • 3
  • 21
  • 34
0

Something like this would be better.

for_each(E item in somelist)
{
     item.doSomeThing();
}

E/Item could be anything(customers, ints, doubles)