Problem with adding objects to ArrayList

Hello,

I wonder how to add object to ArrayList, when some conditions have been fullfiled. For example, i want to add new cell only if my mouse coursor is over one of each cells. Code is here. Thanks in advance :slight_smile:

//Mithosis Simulation
ArrayList<Cell> cell;

void setup() {
  size(600, 600);

  cell = new ArrayList<Cell>();

  cell.add(new Cell());
}

void draw() {
  background(0);

  for (Cell c : cell) {
    c.overlap();
    c.show();
    //c.Add();
  }
}

void mousePressed() {
  for (Cell c : cell) {
    if (c.over) {
      cell.add(new Cell());
    }
  }
}


class Cell {
  float xpos, ypos;
  int r, g, b;
  float rad;
  float d;
  boolean over = false;
  PVector acc;
  PVector vel;

  Cell() {
    this.rad = 15;
    this.xpos = random(rad, width-rad);
    this.ypos = random(rad, height-rad);
    this.r = 255;
    this.g = 0;
    this.b = 200;
    this.vel = new PVector(0, 0);
    this.acc = new PVector(0, 0);
  }

  void show() {
    noStroke();
    fill(r, g, b, 100);
    circle(xpos, ypos, 2*rad);
  }

  void overlap() {

    d = sqrt( pow((xpos-mouseX), 2) + pow((ypos-mouseY), 2) );

    if (d <= rad) {
      r = 0;
      g = 255;
      b = 200;
      over = true;
    } else {
      r = 255;
      g = 0;
      b = 200;
      over = false;
    }
  }

  void devide() {
  }

  void Add() {

    if (mousePressed && over) {
      cell.add(new Cell());
    }
  }
}
1 Like

if (c.over) { :arrow_right: if (c.overlap()) {

I dont get it :confused: Still got this error “ConcurrentModificationException” while i click on the cell

A container being iterated by an “enhanced” for ( : ) loop can’t change it’s size(). :no_entry:

Use a vanilla for ( ; ; ) loop instead: :bulb:

for (int len = cell.size(), i = 0; i < len; ++i)
  if (cell.get(i).overlap())  cell.add(new Cell());
2 Likes