So this is a function from my snake game code. Basically I was initially doing a for to go though the LinkedList<Point>
that is the snake but since it was throwing the exception I thought changing it using iterators would help.
Apparently not.
How can I fix this?
public void drawSnake(Graphics g) {
g.setColor(Color.green);
Iterator<Point> iterator = snake.iterator();
while(iterator.hasNext()){
Point p =iterator.next();
g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
}
g.setColor(Color.black);
}
In general, this exception occurs when collection has been modified while iterating over it.
Most likely that means that snake
is being modified in another thread. This code, considered independently, should not throw CME, so this is the only possible explanation remaining.
Try looking for all usages of snake
variable and analyze whether they can be done together with the code you posted.
Another very, very unlike possibility is that g.fillRect()
method deletes p
from the snake
collection. This can possible if you overrided the method, for example.