The official explanation is here: ArrayList
However, it uses iteration and confuses me.
I am trying to make a drawing pen but something is wrong here:
drawings.get(i) = drawing.get(i-1);
ArrayList <Drawing> drawings = new ArrayList <Drawing>();
void setup(){
size(400,400);
background(255);
colorMode(HSB);
}
void draw(){}
void mouseDragged(){
drawings.add(new Drawing(mouseX,mouseY));
for(int i = drawings.size()-1;i>0;i--){
drawings.get(i) = drawing.get(i-1);
}
for(int i=0;i<drawings.size;i++){
fill(c,100);
drawings.get(i).display();}
}
class Drawing{
float x,y,r;
color c;
Drawing(float ax,float ay){
x=as;
y=ay;
r=random(2,20);
c=color(random(100,200),255,255);
}
void display(){
fill(c,100);
ellipse(drawing[i],r,r);}
}
I still don’t know how to use ArrayList.
Does anyone know?
Thank you.
You mentioned iteration confuses you. It’s a simple for loop. In case you’re having trouble understanding those, they look harder compared to other statements, but that’s just because a loop does 3 things at once:
In your code, there are two loops:
and
The first loop counts backwards, therefore:
i =)drawings.size()
i>0)i--) (or incremented by -1 if you like)drawings.size() simply retrieves the size of the array list (similar to the length property of an array). So in simple terms, the first loop starts with the last element added to the list (the most recent), who’s index is equal to the list size -1 and it stops at the 2nd element, who’s index is 1 (since arrays/array lists start indexing from 0).
The second loop is simpler, since is counts from 0 to the size of the array list, basically all the elements of the list in the order they were stored (oldest to newest).
In the first loop, it looks like you’re shifting all the elements except the first by one.
You should try it like so:
And here is your code listing with the errors fixed:
UPDATE
Because of the reverse loop I assumed you needed to store a list of drawing and offset it, like so:
If you simply want to draw a line between Drawing objects based on distance, you can do it without the reverse loop:
In fact, since you’re not clearing the background, you don’t need a list at all. All you need is a reference to the previous Drawing object so you can check the distance and draw a line:
HTH