So here is my issue, I have an ArrayList, it contains all of the entities that should be rendered to the screen.
It does so like this with a foreach loop.
for (Entity e : entities) {
g.fillRect(x, y, w, h);
}
This works perfectly fine with no errors when it is populated with a lower numbers of values such as 50. That is, the size of the list is 50. However when it is something like 1,000 it throws a ConcurrentModificationException and crashes the app.
I know that the exception means the list has been modified whilst iterating through it, but in that loop is never actually does anything to the list. The list is accessed elsewhere to update things, but shouldn't the foreach loop finish before something else happens that modifies the list?
The list is modified in an update method which updates entities.
The zombies are enemies in a sense and survivors are AI. When a zombie collides with an AI it removed the survivor and replaces it with a survivor. This is the only place the lists are modified.
This all works perfectly when it is dealing with a small number of entities, however with a larger number it crashes.
public void update(double delta) {
for (Zombie z : zombies) {
z.update(delta);
}
for (Survivor s : survivors) {
s.update(delta);
}
List<Survivor> toRemove = new ArrayList<Survivor>();
List<Zombie> toAdd = new ArrayList<Zombie>();
for (Survivor s : survivors) {
for (Zombie z : zombies) {
if (z.collides(s)) {
toAdd.add(new Zombie(s.position, this, zms));
toRemove.add(s);
}
}
}
for (Survivor s : toRemove) {
survivors.remove(s);
}
for (Zombie z : toAdd) {
zombies.add(z);
}
}