How to access the sub-arrays of an Array list?

Hi,

Can someone kindly explain how to access the sub arrays of an ArrayList in Processing Java ?
The example below throws a casting error when I try to get of the sub-arrays at a specific index.

cannot convert from Object to ArrayList

PVector p1 = new PVector(100, 620);
PVector p2 = new PVector(700, 720);
PVector p3 = new PVector(120, 520);
PVector p4 = new PVector(500, 290);

void setup() {
  size(800, 800);
  
  ArrayList tlist = new ArrayList();
  tlist.add(new PVector[]{p1,p2});
  tlist.add(new PVector[]{p2,p3});
  tlist.add(new PVector[]{p3,p4});
  
  for (int i = 0; i < tlist.size(); i++) {
      ArrayList edge = tlist.get(i); //<-- throws an error
  }
}
1 Like

Ok, there are some things missing. First of all, I would suggest to always specify the type of your ArrayList<T>, because it makes working with it way easier and the compiler understands it too.

ArrayList is a generic class which manages list of things. It does not matter if it is an apple or a cat, a list of cats and a list of apples are managed the same way (adding items, removing items, listing items). If you do not specify a type, the ArrayList just uses the most-generic type possible. Because every object in java is a child of Object, it will use this type.

Because you want to store Arrays of Vectors inside your Arraylist, I would suggest you define the type of your list as PVector[]:

ArrayList<PVector[]> tlist = new ArrayList<PVector[]>();

The second problem is, that you try to get an element of the list, but try to store it into the wrong variable type. The following code would only work, if your list contains items which are arraylists too (like ArrayList<ArrayList>).

ArrayList edge = tlist.get(i);

But your list contains arrays of vectors (PVector[]), so it won’t work to cast a PVector[] into a variable of type ArrayList. Change the variable type to PVector[] and your are good to go:

PVector[] edge = tlist.get(i);
4 Likes

Thank you for the swift reply and the comprehensive explanation, it helps a lot.

Here’s my take on it: :flushed:

import java.util.List;
final List<PVector[]> pairs = new ArrayList<PVector[]>();

final PVector[] points = {
  new PVector(50, 310), 
  new PVector(350, 360), 
  new PVector(60, 260), 
  new PVector(250, 145)
};

void setup() {
  size(400, 400);

  PVector p = points[0];
  final int end = points.length;
  int i = 0;

  while (++i < end)  pairs.add(new PVector[] { p, p = points[i] });

  for (final PVector[] pair : pairs)  println(pair);

  exit();
}
1 Like

Now converted to Python Mode: :snake:

pairs = []

points = (
    PVector(50, 310),
    PVector(350, 360),
    PVector(60, 260),
    PVector(250, 145))

def setup():
    size(400, 400)

    p = points[0]

    for i in range(1, len(points)):
        v = points[i]
        pairs.append((p, v))
        p = v

    for pair in pairs: print pair

    exit()
1 Like