Why am I getting java.util.ConcurrentModificationException with an iterator?

matteoiamma

New Member
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:\[code\]Iterator<GameObject> itr = mObjList.iterator(); while (itr.hasNext()) { GameObject obj = itr.next(); // this line gives me the error ... // print object }\[/code\]The only method that adds item to the list, is this:\[code\]public void click(int x, int y) { // adds new object to the list on a click event mObjList.add(new GameObject(x, y));}\[/code\]Most of the times it works. But sometimes I get this error:\[code\]java.util.ConcurrentModificationException\[/code\]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?
 
Top