-1

I'm trying to make an applet of Asteroid objects that float across the screen. If two asteroids collide then the one with the lesser speed is supposed to break up into two smaller asteroids. Once an asteroid is size 1 it should vanish.

When I try to compare two asteroids I get a ConcurrentModificationException and I'm not sure why.

private volatile Collection<Asteroid> belt;
private void handleCollisions() {


    Collection<Asteroid> psuedoBelt = belt;
    Iterator<Asteroid> one;
    Iterator<Asteroid> two;

    for (one = psuedoBelt.iterator(); one.hasNext();) {
        Asteroid aOne = one.next();
        for (two = psuedoBelt.iterator(); two.hasNext();) {

            Asteroid aTwo = two.next();
            if (aOne.collidesWith(aTwo)) {
                if (aOne.getSpeed() > aTwo.getSpeed()) {
                    Collection<Asteroid> split = aTwo.split();
                    two.remove();
                    for (Iterator<Asteroid> three = split.iterator(); three
                            .hasNext();) {
                        psuedoBelt.add(three.next());
                    }
                } else {
                    Collection<Asteroid> split = aOne.split();
                    one.remove();
                    for (Iterator<Asteroid> three = split.iterator(); three
                            .hasNext();) {
                        psuedoBelt.add(three.next());
                    }
                }
            }
        }
    }

    belt = psuedoBelt;

}
TemporaryFix
  • 2,008
  • 3
  • 30
  • 54

1 Answers1

1

First, you create an iterator :

for (one = psuedoBelt.iterator(); one.hasNext();) {

Then, a second one, on the same collection :

    for (two = psuedoBelt.iterator(); two.hasNext();) {

Then, you remove an item with your second iterator :

    two.remove();

The problem is that when you remove the item from the collection, the first iterator (one) is not aware about this removal.

Hence, on one.next(), it detects that the collection has been modified and raises this exception.

There are 2 solutions to that :

  • Try to use only one iterator OR
  • Keep a list of items to remove and remove them after iterating on your collection.
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148