为什么我的 iterator.next 会导致 ConcurrentModificationException?

Why does my iterator.next result in a ConcurrentModificationException?

我正在制作一个游戏,玩家可以吃圆点...这些圆点随机生成,当玩家覆盖圆点时,圆点应该被移除。为此,我使用了迭代器。

ArrayList<Dot> dots = new ArrayList<Dot>();
Iterator<Dot> i = dots.iterator();

public Game(){
    MouseHandler.mouse = new MouseHandler();
    Player.player = new Player(40, 40);

    for(int i = 0; i < 20; i++){
        dots.add(new Dot());
    }
}

public void update(){
    Player.player.update();

    while(i.hasNext()){
        Dot current = i.next();
        if(Player.player.getCircle().intersects(current.getCircle())){
            i.remove();
        }
    }

}

这样做时,我在 Dot current = i.next();

处得到一个 ConcurretModificationException

这个问题的原因是什么,为什么会这样?

-真诚的亨里克

编辑: 抱歉这么麻烦我只是想让代码更短更易读。

EDIT2: 谢谢大家...问题是我在创建迭代器之前没有向集合中添加任何内容。感谢大家的帮助!

您遇到异常是因为您是直接修改集合而不是通过迭代器。

您可以使用 i.remove() 从迭代器中移除。

您正在初始字段分配中创建迭代器,这可能发生在您向构造函数中的集合添加任何内容之前。

删除迭代器字段并仅在 while 循环之前调用 dots.iterator(),分配给局部变量。