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.