im having a problem i havent been able to figure out a solution to. Im making a small game where the object in _sballs ArrayList will be deleted if collided with another object called ball.
the problem i’ve encountered is that when the collision occur and when i attempt to remove the object from the ArrayList, the application crashes.
for(GObject sballgraphic : _sballs){
Coordinates sballcoords = sballgraphic.getCoords();
if(coords.getY() - coords._height > sballcoords.getY() + sballcoords._height && coords.getX() - coords._width > sballcoords.getX() + sballcoords._width){
_sballs.remove(sballgraphic);
}
}
So the code compares the balls coordinates with all the sballs objects to check if there is a collision, then tries to remove the sball.
What is the problem here? 🙂
I’m guessing that the “crash” is a
ConcurrentModificationException.It is happening because you are trying to remove from a collection while you are iterating over it with an iterator (the internal workings of the enhanced for).
Your choices are:
for( i=0; i<_sballs.size(); i++ ))remove()method.removeAll()after the loop is finished.