Here is an implementation:
Code:class Ellipse implements Comparable
{
int x, y, w, h;
color fc, sc;
int dl; // 0 to 10
Ellipse(int x, int y, int w, int h, int dl)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.dl = dl;
// Can add a setter for fc, sc, and/or put them in constructor,
// or leave direct access (not a very good idea, OK for quick test
fc = color(255 * dl / maxColorNb);
sc = color(255 * (maxColorNb - dl) / maxColorNb);
}
public int compareTo(Object o)
{
if (!(o instanceof Ellipse))
throw new ClassCastException();
int odl = ((Ellipse) o).dl;
if (odl < dl)
return 1;
if (odl > dl)
return -1;
return 0;
}
public String toString()
{
return "Ellipse[" + x + ", " + y + ", " + w + ", " + h + ", " + dl + "]";
}
public void draw()
{
fill(fc);
stroke(sc);
ellipse(x, y, w, h);
}
}
ArrayList al = new ArrayList();
int mn = 50, mx = 200;
int maxColorNb = 20;
void setup()
{
size(800, 800);
for (int i = 0; i < 100; i++)
{
Ellipse e = new Ellipse(
int(random(mx, width - mx)),
int(random(mx, height - mx)),
int(random(mn, mx)),
int(random(mn, mx)),
int(random(0, maxColorNb))
);
al.add(e);
}
Collections.sort(al);
println(al.size());
}
void draw()
{
background(128, 200, 255);
Iterator iter = al.iterator();
while (iter.hasNext())
{
Ellipse e = (Ellipse) iter.next();
e.draw();
}
}
Another approach, if you need to add ellipses in real time, is to make a class extending ArrayList, with an add method inserting the object in its right place, thus avoiding to re-sort each time.