08. ArrayList, Iterators, Particle systems



While removing elements from the ArrayList during a loop we skip one element. When an object is removed from the ArrayList during a loop, all elements are shifted one spot to the left and one element is skiped.

each-00000

source code

The solution is either loop backwards or use Iterator.

Backward loop:

 for (int i = particles.size()-1; i >= 0; i--) {
    Particle p = (Particle) particles.get(i);
    p.run();
    if (p.isDead()) {
      particles.remove(i);
    }
  }


Iterator:

import java.util.*;  //you have to import this library

  Iterator it = particles.iterator();
Using an Iterator object instead of counting with int i
  while (it.hasNext()) {
    Particle p = it.next();
    p.run();
    if (p.isDead()) {
       it.remove();
    }
  }


each-00000

01.Particles stored in ArrayList:

02.Particle system class:

03.System of systems:

See for more:
07. Attraction
Nature of code



Comments are closed.