How to remove multiple elements in an array in libgdx

I am using libgdx, I have a class class created by me. I am trying to remove balls of the same color at a time. due to a shift in the position of the elements in the array after deleting the element, this leaves some element restored. so I use Snapshot Arrays https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/SnapshotArray.html

according to the size of the documentation array and indexes it will not change if we write our loop between the array.begin () and array.end () methods. so I declared snapshot arrays

SnapshotArray<Ball> balls;

and my removal method

 private void removeVillianGroups(int color){
        Ball[] ball=balls.begin();
        for(int i=0;i<balls.size;i++){

            if(balls.get(i).getColor()==color){
                ball.removeValue(balls[i],true);

            }
        }
        balls.end();
    }

and I get an error when casting

 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.mygames.haloween.Entity.Ball;

on this line above

Ball[] ball=balls.begin();

So, I created my array, basically I divide my screen width into six equal parts to have 6 columns of balls

 private void createVillians() {

      for (int color=0;color<4;color++)//create 4 diffirent color balls in 4 rows
        for(int i=0;i<6;i++)//each row contan 6 same color balls
{
       balls.add(new Ball(viewport,new Vector2(i*viewport.getWorldWidth()/6,
               0-c*viewport.getWorldWidth()/6),color));

//Ball class just draw balls according their color between 0 to 3.
        }
    }

this is what is generated by this array

+4
2

ArrayList :

ArrayList<Ball> balls;

private void removeVillianGroups(int color){
  for(int i = balls.size() - 1; i >= 0; i--){
        if(balls.get(i).getColor()==color){
            balls.remove(i);
        }
    }
}
+1

, CCE, , libgdx Array/SnapshotArray Object [], . SnapshotArray , Array ArrayList, .

, . , balls.size , . :

private void removeVillianGroups(int color){
    Ball[] ball=balls.begin();
    for(int i=0, n=balls.size; i<n; i++){
        if(ball[i].getColor()==color){
            balls.removeIndex(i);
        }
    }
    balls.end();
}
+1

Source: https://habr.com/ru/post/1673233/


All Articles