user1295313
user1295313

Reputation: 65

Crash when trying to remove object from ArrayList

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

Answers (2)

trutheality
trutheality

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:

  1. Iterate using an index (old-style for( i=0; i<_sballs.size(); i++ ))
  2. Iterate using an iterator explicitly, and use the iterator's remove() method.
  3. Remember which items to remove by putting them into another list, and then use removeAll() after the loop is finished.

Upvotes: 6

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

Related Questions