簡體   English   中英

為什么我的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 Dot current = i.next();

此問題的原因是什么,為什么會發生?

-真誠的Henrik

編輯:很抱歉這么麻煩,我只是想使代碼更短,更易讀。

EDIT2:謝謝大家...問題是在創建Iterator之前,我沒有向集合中添加任何內容。 感謝您的所有幫助!

之所以會出現異常,是因為直接修改集合而不是通過迭代器。

您可以改為使用i.remove()從迭代器中刪除。

您正在初始字段分配中創建迭代器,這大概是在向構造函數中的集合添加任何內容之前發生的。

刪除iterator字段,然后僅在while循環之前調用dots.iterator() ,將其分配給局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM