Kharak
Kharak

Reputation: 384

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

Upvotes: 4

Views: 882

Answers (2)

Tenfour04
Tenfour04

Reputation: 93789

The reason your original code was giving a CCE is that the libgdx Array/SnapshotArray class returns an Object[] if you did not pass in the class type in its constructor. SnapshotArray is potentially faster than Array or ArrayList if you are removing several items at once.

You seem to be mixing up the snapshot array with the temporary array, as well. And note that balls.size is not stable during iteration, so you should cache it. Your code should look like this:

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

Upvotes: 1

Stefan Haustein
Stefan Haustein

Reputation: 18803

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

Upvotes: 1

Related Questions