0

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);
}
6
  • 2
    Are you sure this is the code throwing the exception? Doesn't seem likely at all to me. Commented May 17, 2014 at 9:08
  • 2
    Agree with @kviiri , there's no modification in this example, so this should not throw any Exception. Commented May 17, 2014 at 9:12
  • 1
    this may help you stackoverflow.com/questions/8189466/… Commented May 17, 2014 at 9:20
  • @kviiri I do udnerstand what you are saying since there are no (at least visible) modifications to the snake in that function but the error points towards it :/ Commented May 17, 2014 at 9:53
  • 1
    @Asura14, post the stack trace of the exception, it might have something of interest. Commented May 17, 2014 at 10:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.