You can remove objects from the ArrayList which you are using. I use this in my game engine and it works.
See http://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/map/Map.java#350
for (int i = 0; i < objects.size(); i++) {
GObject other = objects.get(i);
if (other.isAlive()) {
// Update it
} else {
// Else remove it
objects.remove(i);
}
}
What the error you are having is this does not work for the for each
loop. Try in a normal for
loop and that should solve your problem.
Change your code to this.
ArrayList<Integer> list =new ArrayList<Integer>();
ArrayList<Integer> remove = new ArrayList<Integer>();
list.add(100);
list.add(200);
list.add(300);
list.add(400);
// Mark to remove
for (int i=0; i<list.size(); i++){
remove.add(list.get(i));
}
list.removeAll(remove);
remove.clear();
// adding 200 at the end because if added in the loop,
// it removes the 200 and adds every loop which causes
// unnecessary memory usage.
list.add(200);