LibGdx, update list while iterating through it

IS there a way to add and delete elements from a ArrayList while im iterateing through it ? Or is there some other Array Type for it?

ehhhh…


    for(Thing thing: aListOfThings){
        thing.update();
        if(thing.hasDoneSomethingBad)
            aListOfThings.remove(thing, true);
}

Unless I am missing something here?

@Gibbo If I’m not mistaken, that’ll throw a ConcurrentModificationException

@OP: http://www.java-gaming.org/topics/concurrentmodificationexception-when-removing-an-item-from-an-arraylist/32939/view.html
A few solutions here, an iterator is probably the most fool-proof.

This works for removing. What about adding. IM iterating through my Array of Entities, and at one point entity must add ned entitis to the list. On the moment of addition i get the error. Array is static and the addition happen in another class.

Hmmm, does not seem to with LibGDX Array.

For instance in my breakout game I am iterating through the Array of Blocks, to check if Ball overlaps a Block, if so remove from array. It gets removed during iteration.

That’s because LibGDX’s developers took care if this issue, but with Java’s built-in collections you can not modify a collection while you’re iterating over it using a for-each loop.

To the OP: Use ListIterators. They can both remove and add elements to the collection during iteration. :slight_smile:

I have it setup like this, and im still gettign the error message. These 2 codes are in different classes.

	    ListIterator<Entity> iter = entitys.listIterator();
	    while(iter.hasNext()){
	    	Entity e = iter.next();
	    	e.update(delta);
	    	if(!e.onScreen()){
	    		iter.remove();
	    	}
	    }
public class Shoot {
	
	public Shoot(float x, float y){
		GameWorld.entitys.add(new CircleBullet(x,y, 0, 10));
		GameWorld.entitys.add(new CircleBullet(x,y, 5, 10));
	}
}

So why is the OP using an ArrayList and not an Array<?>…

Problem solved. Using Array worked. Just asking, is there a better way to fill an array in other class other than declaring it static?