ArrayList out of boundary

Hi,
Playing with objects and ArrayList.

I’ve trouble removing objects from the ArrayList when they disappear from the screen.
IndexOutOfBoundsException: Index: 49, Size: 49

ArrayList<Bubble> bubble = new ArrayList<Bubble>();

//Bubble bubble;
float speed;
float dia;
float x, y;
int numberB = 50;

void setup() {
  size(400, 400, P2D);

  y = height- (0.5 * dia);

  for (int i = numberB -1; i >= 0; i--) {
    x = random(dia, width-dia);
    speed = random(0.2, 1.2);
    dia = random(5, 30);
    bubble.add(new Bubble(x, y, dia, speed));
  }
  //bubble = new Bubble(random(10, 50), random(1,3));
}


void draw() {
  background(0);
  for (int i = numberB -1; i >= 0; i--) {

    Bubble bub = bubble.get(i);
    bub.display();
    bub.move();
    if (bub.mode == 1) {
      bubble.remove(i);
      println("removed");
    }
    //bubble.get(i).disappear(i);
  }
}


class Bubble {
  float x, y, diameter, yspeed;
  int mode = 0;

  Bubble(float tempX, float tempY, float tempDiameter, float tempYspeed) {


    diameter = tempDiameter;
    yspeed = tempYspeed;
    x = tempX;
    y = tempY;
  }

  void display() {
    //fill(255);
    noFill();
    stroke(255);
    ellipse(x, y, diameter, diameter);
  }

  void move() {
    
    y -= yspeed;
    if (y + dia < 0) {
     mode = 1;
    println("mode = 1");
    //}
  }
  }

  boolean disappear() {
    if (y + dia < 0) {
      return true;
    } else {
      return false;
    }
  }
}

Try:

for (int i = bubble.size() -1; i >= 0; i--)

Give it some thought and you will understand why.

:)

I like the way you answer with a question :wink:

I assume it’s because bubble.size() is flexible, where the variable numberB is fixed and so when a item is removed from the ArrayList, numberB should change, like is now done with bubble.size().

Hello,

References for you to explore:
https://processing.org/reference/ArrayList.html
Googe Search for ArrayList Processing

:)