我遇到并发修改异常的问题。我已将代码更改为使用迭代器,但是当我删除对象时仍然遇到这些问题。我的错误发生在线
theEnemy = (Enemy) EnemyItr.next();
我不确定如何解决这个问题,因为它是代码中非常重要的一部分。
for (Iterator EnemyItr = activeEnemies.iterator(); EnemyItr.hasNext(); ){
theEnemy = (Enemy) EnemyItr.next();
try {
try {
if (theEnemy.x < 0 && theEnemy.y >= 5) {
activeEnemies.remove(theEnemy);
}
} catch (Exception e) {
System.err.println("Cannot Remove Enemy");
}
Enemy.pathFind(Enemy.getXBlockOfEnemy(theEnemy.x), Enemy.getXBlockOfEnemy(theEnemy.y), theEnemy.x, theEnemy.y);
if (Enemy.right) {
theEnemy.x += Enemy.speed;
//System.out.println("right");
//System.out.println(theEnemy.x + " " + theEnemy.y);
} else if (Enemy.down) {
theEnemy.y += Enemy.speed;
//System.out.println("down");
//System.out.println(theEnemy.x + " " + theEnemy.y);;
} else if (Enemy.up) {
theEnemy.y -= Enemy.speed;
//System.out.println("up");
//System.out.println(theEnemy.x + " " + theEnemy.y);
} else if (Enemy.left) {
theEnemy.x -= Enemy.speed;
//System.out.println("left");
//System.out.println(theEnemy.x + " " + theEnemy.y);
} else {
System.out.println("Enemy Lost.");
//System.out.println(theEnemy.x + " " + theEnemy.y);
}
g.drawImage(enemy, theEnemy.x, theEnemy.y, this);
//System.out.println(Enemy.getXBlockOfEnemy(theEnemy.x));
//drawing health bar
if (Input.displayUI) {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(theEnemy.x, theEnemy.y - 10, 70, 10);
g.setColor(Color.RED);
g.fillRect(theEnemy.x + 2, theEnemy.y - 10 + 1, 68, 8);
g.setColor(Color.GREEN);
g.fillRect(theEnemy.x + 2, theEnemy.y - 10 + 1, (int) (.68 * theEnemy.enemylife), 8);
}
} catch (ConcurrentModificationException e) {
theEnemy = null;
}
}