java - 迭代Java时从数组中删除对象

标签 java arraylist foreach iterator

我正试图在碰撞时同时删除飞船和炮弹。 为此,我迭代了两个高级 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/

相关文章:

javascript - Ember js 检查对象数组中的键值

java - 静态错误: This class does not have a static void main method accepting String[].

java - 跳过循环中的第一行

Java FX - 如何创建没有内容的标签以在布局管理器中保留位置?

java - 将监听器添加到 ArrayList

java - 在 ArrayList 的 ArrayList 中查找唯一的 Arraylist

java - 如果该行包含字符串匹配的任何部分,则使用扫描仪显示整行(Java)

php - 如何在 if 语句中添加查询结果限制?

PHP Foreach 循环从循环内部向前迈进了一步

java - 清空后重新填充数组列表