我正试图在碰撞时同时删除飞船和炮弹。 为此,我迭代了两个高级 for 循环,并尝试在它们相交时删除它们。不幸的是,在迭代循环时编辑 for 循环并不是一个好主意,它会抛出 ConcurrentModificationException,所以我将它们换成迭代器,这似乎有效。
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;
}
}
}
}
}
问题是 ConcurrentModificationException 似乎已经移动到我调用更新程序的地方。我也尝试将那些 for 循环换成迭代器,但它似乎不起作用并抛出相同的异常,但现在在 update() 方法中。
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);
}
}
我应该改变更新游戏对象的方式还是保存它们的方式?还是我以错误的方式删除了对象?
最佳答案
您可以将那些发生碰撞的变量保存到某个变量中,然后在完成循环后,将它们从列表中移除:
Ship shipToRemove = null;
Projectile projToRemove = null;
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)) {
shipToRemove = ship;
projToRemove = proj;
break;
}
}
}
}
Projectile.projectiles.remove(projToRemove);
Ship.ships.remove(shipToRemove);
应该怎么做。
关于java - 迭代Java时从数组中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475222/