I'm trying to delete both a ship and a projectile when they collide. To do this I'm iterating through two advanced for-loops and I try to delete them when they intersect. Unfortunately edditing for-loops while iterating through them isn't a good idea and it throws an ConcurrentModificationException, so I switched them out for Iterators, which seems to be working.
public void collision()
{
Iterator<Ship> itShips = Ship.ships.iterator();
Iterator<Projectile> itProj = Projectile.projectiles.iterator();
while (itShips.hasNext()) {
Ship ship = itShips.next();
while (itProj.hasNext()) {
Projectile proj = itProj.next();
if (ship.c != proj.c) {
Rectangle.Float r1 = ship.getBounds();
Rectangle.Float r2 = proj.getBounds();
if (r1.intersects(r2)) {
itProj.remove();
itShips.remove();
break;
}
}
}
}
}
the problem is that the ConcurrentModificationException seems to have moved to where I call my updaters. I tried swapping those for-loops out for iterators as well, but it doesn't seem to work and throws the same exception but now in the update() method.
public void update()
{
Iterator<Ship> it1 = Ship.ships.iterator();
while (it1.hasNext()) {
Ship s = it1.next();
s.update(game);
}
Iterator<Projectile> it2 = Projectile.projectiles.iterator();
while (it2.hasNext()) {
Projectile p = it2.next();
p.update(game);
}
}
Should I change the way I update my gameobjects or the way I save them? Or am I doing the deletion of the objects the wrong way?