简体   繁体   中英

Why does my iterator.next result in a ConcurrentModificationException?

I am making a game where you as a player eat dots... These dots spawn randomly and when the player covers the dots they should be removed. To do this I am using an Iterator.

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();
        }
    }

}

When doing this i get a ConcurretModificationException at the Dot current = i.next();

What is the cause of this problem, why is it happening?

-Sincerely Henrik

EDIT: Sorry for being so troublesome I was just trying to make the code shorter and more readable.

EDIT2: Thanks everyone... The problem was that I had not added anything to the collection before creating an Iterator. Thanks for all the help!

You are getting the exception because you are modifying the collection directly and not via the iterator.

You can remove from the iterator using i.remove() instead.

You are creating the iterator in the initial field assignment, which is presumably happening before you add anything to the collection in the constructor.

Remove the iterator field and just call dots.iterator() , assigning to a local variable, immediately before the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM