Array Lists creating/removing objects in a class

Hi I am wondering how to create objects from a classes method and what a ConcurrentModificationException is and why I’m getting it. I am a student and I am confused to why I keep getting this error in my code.

ArrayList<Object> objects = new ArrayList<Object>();

void setup() {
    size(800,600);
}
void draw() {
    background(0);
    for (Object objects : objects) {
        objects.update();
    }
}
void mousePressed() {
    objects.add(new Object(100,400));
}

class Object {
    float x,y;
    Object(float tempX, float tempY) {
        x = tempX;
        y = tempY;
    }
    void update() {
        x = x + 5;
        ellipse(x,y,25,25);
        if (x > width) objects.remove(this);
    }
}

This isn’t the exact code but its the same idea so basically I want it to remove the object when it goes off the screen but as soon as the object goes off the screen it crashes and redirects me to the for loop in the draw loop and spits a ConcurrentModificationException at me, heres another example.

ArrayList<Object> objects = new ArrayList<Object>();

void setup() {
    size(800,600);
}
void draw() {
    background(0);
    for (Object objects : objects) {
        objects.update();
    }
}
void mousePressed() {
    objects.add(new Object(100,400));
}

class Object {
    float x,y;
    int timer=50;
    boolean duplicated=false;
    Object(float tempX, float tempY) {
        x = tempX;
        y = tempY;
    }
    void update() {
        x = x + 5;
        ellipse(x,y,25,25);
        if (timer <= 0 && duplicated == false) {
            duplicated = true;
            objects.add(new Object(100,y-50));
        } else timer--;
    }
}

So basically in this similar example inside of the objects update loop it attempts to create a new object to the arraylist but as soon as it reaches that point it crashes and spits another ConcurrentModificationException, now I am no expert and gained most of my knowledge from google but I couldn’t find anything on this type of situation so please any help or just explanation of why I’m getting this error would be greatly appreciated. I did not test this code and just typed it out but this code should work so give it a try if you want.

1 Like

Good news I figured out a way around the ConcurrentModificationException although I don’t think it’s very reliable, so what I changed was the draw loop to this:

void draw() {
    background(0);
    for (int i=0; i < objects.size(); i++) {
      objects.get(i).update();
    }
    println(objects.size());
}

If anyone could point out a better method to this then counting up it would be gladly appreciated!

2 Likes

Your error was caused by the enhanced for loop you used:

// If you are modifying an ArrayList during the loop,
// then you cannot use the enhanced loop syntax.
(source: ArrayList / Reference / Processing.org)

I think the page I linked you solves some of your confusion and questions :slight_smile:

3 Likes