1

Using the following code will result in a java.util.ConcurrentModificationException

final AnimationTimer timer = new AnimationTimer() {
    @Override
    public void handle(long timestamp) {


        for (ListIterator<myCircle> List = CircleList.listIterator(); List.hasNext(); ) {
            myCirle check = List.next();

            if (CheckCollisionFunction(check) == true) {
                this.stop();
                CircleList.clear();
                gameOverFunction();
            }
        }
    }
} 

So im using an iterator to check if any of my circles are colliding with my player circle.

When I clear the list:

CircleList.clear();

I get the exception.

java.util.ConcurrentModificationException

Which is when you delete sometimes outside an iterator when using an iterator. Can someone please show me how to delete everything in my list using the iterator?

Or another way to stop this error.

This is my list.

private final ObservableList<myCircle> CircleList = FXCollections.observableArrayList();
Dynermite
  • 189
  • 2
  • 13
  • 1
    Where are you calling clear() from? There's no reason to remove elements one by one via the iterator. You just have to call clear() after you are done with iterating over the List. – Eran Feb 08 '17 at 12:16
  • final AnimationTimer timer = new AnimationTimer() { @Override public void handle(long timestamp) { Everything is in this timer but i also use this.stop(); to stop the animation timer. – Dynermite Feb 08 '17 at 12:18
  • 1
    Are you clearing the list from a different thread than the one that iterates over the list? That would explain the exception. – Eran Feb 08 '17 at 12:21
  • Edited to show that there all in the same place. im also using two iterators under the same timer. One checks for wall collisions one checks for circle collisions could that be an issue? I could put them in the same iterator i dont know why i havent tbh. – Dynermite Feb 08 '17 at 12:27

1 Answers1

3

Simply insert a break; after gameOverFunction(); to stop the iterator.

The problem is that you clear the list, but the iterator continues, and on the next next() call the exception will be thrown.

DVarga
  • 21,311
  • 6
  • 55
  • 60