Appending to arrays of arrays

Well, here is one example. You have an unknown number of layers, and each layer is full of an unknown number of points, and each point contains 2 or 3 floats (2D or 3D). It should be easy to add layers and points, and get them.

ArrayList<ArrayList<PVector>> layers;

Okay, initialize your layers – a list of (lists of (points)).

layers = new ArrayList<ArrayList<PVector>>();

and add a layer – which is a list of points:

layers.add(new ArrayList<PVector>());

now get layer 0

ArrayList<PVector> layer0 = layers.get(0);

and add some points to layer 0

layer0.add(new PVector(0, 0));
layer0.add(new PVector(50, 50));
layer0.add(new PVector(random(0, width), random(0, height)));

now retrieve layer 0, point 1 from your layers object:

PVector pt = layers.get(0).get(1);

and draw its x, y:

ellipse(pt.x, pt.y, 20, 20);

The example:

ArrayList<ArrayList<PVector>> layers;
layers = new ArrayList<ArrayList<PVector>>();
layers.add(new ArrayList<PVector>());
ArrayList<PVector> layer0 = layers.get(0);
layer0.add(new PVector(0, 0));
layer0.add(new PVector(50, 50));
layer0.add(new PVector(random(0, width), random(0, height)));
PVector pt = layers.get(0).get(1);
ellipse(pt.x, pt.y, 20, 20);
1 Like