I use an arrayList to store points making a polyline and I want to replace the points each time I press the mouse button.
Instead of using a for loop to iterate through the arrayList and remove the items one by one using the remove method I recreate the arrayList instead. Is it a good practice or not?
int numPoints = 10;
ArrayList<Point> MesPoints = new ArrayList();
void setup() {
size(900, 900);
background(0);
}
void draw() {
background(0);
stroke(255,0,0);
strokeWeight(5);
for (int i = 0; i < MesPoints.size()-1; i++) {
Point oldp = MesPoints.get(i);
Point newp = MesPoints.get(i+1);
line(oldp.pos.x, oldp.pos.y, newp.pos.x, newp.pos.y);
}
}
void mousePressed() {
MesPoints = new ArrayList(); // important! Recreation of the arraylist to clean it!
for (int i = 0; i < numPoints ; i++) {
Point np=new Point();
np.pos=new PVector(random(width), random(height));
MesPoints.add(np);
}
}
class Point {
PVector pos;
}
Haha. Great @glv! But I wonder if recreating the arrayList is more efficient or not as both clear() and removeAll() imply some iteration whereas a full recreation doesn’t I guess.