Reputation: 65
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? :)
Upvotes: 0
Views: 2570
Reputation: 23465
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.Upvotes: 6
Reputation: 42026
You cant do such operation because you are modifying the same _sballs
onwhich you are iterating too.
ArrayList<GObject> _sballs;
ArrayList<GObject> _sballsForRemove;
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){
_sballsForRemove.add(sballgraphic);
}
}
_sballs.removeAll(_sballsForRemove);
Upvotes: 1