1

I am doing some kind of arkanoid, and I got stuck. The way I do it is through JFrame, JPanel and with Timer. So what I do each timer update is this

 public class Controller implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
       ball.move();
       desk.move();
       deskCollision();
       squareCollision();
       repaint();

    }  
}

I created Arraylist of squares, and I printed them. When I check the collision with squares and ball, it works. So now I want to remove a specific square, when a ball hits it and change direction of a ball. Firstly, I tried it without any kind of a loop, like this.

if(ListOfSquares.get(24).getBounds2D().intersects(ball.getBounds2D())){
        ball.dy = 1;
        ball.dx = -1;
        ListOfSquares.remove(24);
    }

This works as well. But as I want to make a loop which will go trough all of the squares and always remove the specific square, I am lost. I have done it like this, but it ends up with a bug -- Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException --

  for(Square square : ListOfSquares){
       int index = ListOfSquares.indexOf(square);
       if (ball.getBounds2D().intersects(square.getBounds2D())) {
           if(ball.dx == -1 && ball.dy == -1){
           ball.dy = 1;
           ball.dx = -1;
           ListOfSquares.remove(index);
           }
           //etc...
       }
   }          

Thanks for your help.

Jindřich
  • 27
  • 1
  • 4

1 Answers1

1

Iterator may help you:

Iterator<String> iter = ListOfSquares.iterator();

while (iter.hasNext()) {
    Square squ = iter.next();

    if (someCondition)
        iter.remove();
}

Refference:How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

Community
  • 1
  • 1
Dai Kaixian
  • 1,045
  • 2
  • 14
  • 24