Collection Problem

I’m trying to implement a particle system in my game, but have run into a snag.

I store all created Emitters in a List . Each update cycle I iterate through all of them and have them emit unless their timeToLive has expired, in which case I need to remove them from the list. But, If I try to remove a dead Emitter in the for loop where I’m iterating through them, I get an exception.

Here is the problematic code.


for(Emitter emitter : emittersList) {

            if(emitter.isDead()) {
                emittersList.remove(emitter);         // Causes Runtime Error
            }
            else {
               emitter.emit(elapsedMS, particlesList); 
            }
}

My current solution is to add another list which holds all dead Emitters that need to be removed, and then remove them all after iterating through.

Like this.


for(Emitter emitter : emittersList) {

            if(emitter.isDead()) {
                deadEmittersList.add(emitter);
            }
            else {
               emitter.emit(elapsedMS, particlesList); 
            }
}

emittersList.removeAll(deadEmittersList);
deadEmittersList.clear();


So, is there a solution for this, that is more efficient and doesn’t require a seperate Dead Emitter list?

Use Iterators. You can remove the last item returned by the iterator’s next() method while you are in the loop, as long as you do it using the iterator and don’t access the list directly.

http://www.java-gaming.org/forums/index.php?topic=12360.msg98794#msg98794

Keep in mind that the index variable will point at something else after the remove() bit. So, if you want to do something with it do it before removal (obviously).

The interesting stuff in that thread are Jeff’s and my posts. Ignore the rest.

Took care of the problem. Thanks for the help guys.