Search code examples
javaarrayslibgdx

how to remove multiple elements in array in libgdx


I am using libgdx, i have an arraylist of ball class created by me. i am trying to delete balls with same color at a time. due to shift in position of elements in array after deletion of element, this leave some element undelete. so i am using Snapshot Arrays https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/SnapshotArray.html

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

SnapshotArray<Ball> balls;

and my deletion method is

 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 am getting error with casting

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

at this line above

Ball[] ball=balls.begin();

So here i created my array,basically i divide my screen width into six equal part, to have 6 column 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 generate by this array


Solution

  • Can't you just use a regular ArrayList and iterate backwards:

    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);
            }
        }
    }