clearing an ArrayList

edited September 2018 in Library Questions

I've around this issue a few times. I have a particle system that contains an ArrayList of particles. I use a separate window for the interface programmed using Control P5.

usually my particle system lies under a boolean, and that boolean is activated/deactivated by a cp5 toggle. every time i toggle it to false, i want the ArrayList inside the particle system to be cleared, so the particle system starts fresh from zero instead of a simple interruption it's runtime.

so i put a ps.particles.clear(); in the toggle false condition. everytime it crashes and I get IndexOutOfBoundsException. it also happened to me with a bang and a button.

what is the most efficient way to really clear an ArrayList?

here is the code with whats going on.

main code

import controlP5.*;
ControlFrame cf;
RingSystem r;

boolean isRing = false;

void settings(){
   size(600,600);
}    

void setup(){

     //CONTROLP5
     cf =new ControlFrame(this, 400, displayHeight, "MENU", width, height);

     //RING SETUP
     cPos=new PVector(width/2, height/2, 0);
     r=new RingSystem(cPos);
}

void draw(){
  if (isRing) {
    if (frameCount%30==0) r.addRing();
    r.display();
  }
}

Ring System

class RingSystem{
 ArrayList<Ring> rings;
 PVector origin;
 RingSystem(PVector _origin){
   rings=new ArrayList<Ring>();
   origin=_origin.copy();
 }

 void addRing(){
  rings.add(new Ring(origin)); 
 }

 void display(){
   for(int i=rings.size()-1; i>0; i--){
    Ring r=rings.get(i);
    r.update();
    r.display();
    if(r.isDead()){
     rings.remove(i); 
    }
   }
 }
}

Ring/Particle

class Ring {
  PVector origin;
  float dim=0;
  float dimMax=400;
  float life=0;
  float alpha;

  Ring(PVector _origin) {
    origin=_origin.copy();
  }

  void update() {
    life++;
    //origin.y++;
    //dim=cos(radians(life))*life;
    dim=life;
    alpha=map(life,height*2,0,0,255);
  }

  void display() {
    pushMatrix();
    stroke(0, 255, 255,alpha);
    strokeWeight(6);
    noFill();
    translate(origin.x, origin.y, origin.z);
    //rotateX(radians(90));
    ellipse(0, 0, dim, dim);
    popMatrix();
  }

  boolean isDead() {
    if (life>height*2) {
      return true;
    } else {
      return false;
    }
  }
}

Control Frame

public class ControlFrame extends PApplet {

  ControlP5 cp5;
  Object parent;

  public void setup() {
    cp5 = new ControlP5(this);  

    cp5.addToggle("ringToggle")
      .setPosition(160, 50)
      .setSize(80, 80)
      .setValue(false)
      ;
}
  void ringToggle(boolean toggle) {
    if (toggle==true) {
      isRing=true;
    } else {
      isRing=false;

      r.removeAll(rings);
      for (int i=0; i<r.rings.size(); i++) {
        Ring ri=r.rings.get(i);
        r.rings.remove(i);
      }
    }
  }

}

Answers

Sign In or Register to comment.