我正在尝试制作一个简单的javagame。其中一个方法创建一个具有随机x和y值的新矩形,然后将它们添加到列表中。 我希望我的程序检查是否要添加的新矩形是否与当前的一个相交,如果是,它应该得到新的x和y值。
我已经制作了一个应该可行的方法,但不管怎么说,它都没有,我得到了错误:
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException.
该方法的代码是:
public void addObstacle() {
int x = (int)((Math.random() * 10)) * 40;
int y = (int)((Math.random() * 10)) * 20;
Rectangle newRec = new Rectangle(x, y, 20, 20);
for(Rectangle r : obstacles) {
if(newRec.intersects(r)) {
System.out.println("The new rectangle does intersect with " + r);
}
else {
obstacles.add(newRec);
}
}
repaint();
}
提前致谢。
更新:通过添加:
修复 Boolean doesCollide = false;
for(Rectangle r : obstacles){
if(newRec.intersects(r)){
System.out.println("The new rectangle does intersect with " + r);
doesCollide = true;
}
}
if(!doesCollide){
obstacles.add(newRec);
}
答案 0 :(得分:2)
当您尝试在循环上修改集合时会发生这种情况。在obstacles.add(newRec);
循环时,您正在obstacles
进行操作。您可以使用ListIterator
来修改集合。这样你就不会得到这个例外