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
  • 289,723
  • 53
  • 439
  • 496
Michael Kohler
  • 753
  • 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,053
  • 3
  • 23
  • 36
0

Something like this would be better.

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

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