I'm trying to write a game, so every frame I call the doDraw() method where I'm using an iterator to loop through all GameObjects and print them all on screen:
Iterator<GameObject> itr = mObjList.iterator();
while (itr.hasNext()) {
GameObject obj = itr.next(); // this line gives me the error
...
// print object
}
The only method that adds item to the list, is this:
public void click(int x, int y) {
// adds new object to the list on a click event
mObjList.add(new GameObject(x, y));
}
Most of the times it works. But sometimes I get this error:
java.util.ConcurrentModificationException
From the line with "itr.next()". From what I've googled, I figured this is because the click() event sometimes happen before the draw() finishes drawing every object, so it's changing the list while the iterator is using it. I suppose this is what's wrong?
But I'm not experienced with threads. How could I possibly fix this? Maybe I'm doing this whole thing wrong and I should use a completely different method to print all objects on screen?