开发者

Processing language: Get inner array values from ArrayList()

开发者 https://www.devze.com 2023-04-12 13:38 出处:网络
I\'m trying to use the ArrayList() method in Processing. I have this: ArrayList trackPoints = new ArrayList();

I'm trying to use the ArrayList() method in Processing.

I have this:

    ArrayList trackPoints = new ArrayList();

        //inside a loop
        int[] singlePoint = new int[3];

        singlePoint[0] = 5239;
        singlePoint[1] = 42314;
        singlePoint[2] = 1343;
        //inside a loop

    trackPoints.add(singlePoint);

So basically I want to add an array "singlePoint" with three values to my ArrayList.

This seems to work fine, because now I can use println(trackPoints.get(5)); and I get this:

[0] = 5239;
[1] = 42314;
[2] = 1343;

However how can I get a single value of this array?

println(trackPoints.get(5)[0]); doesn't work.

I get the following error: "The type of the expression must be an array type but it resolved to Object"

Any idea what I'm doing wrong? How can I get single values from this arrayList with multiple array开发者_JS百科s in it?

Thank you for your help!


Your ArrayList should by typed :

List<int[]> list = new ArrayList<int[]>();

If it's not, then you're using a raw List, which can contain anything. Its get method thus returns Object (which is the root class of all the Java objects), and you must use a cast:

int[] point = (int[]) trackPoints.get(5);
println(point[0]);

You should read about generics, and read the api doc of ArrayList.


The get() method on ArrayList class returns an Object, unless you use it with generics. So basically when you say trackPoints.get(5), what it returns is an Object.

It's same as,

Object obj = list.get(5);

So you can't call obj[0].

To do that, you need to type case it first, like this:

( (int[]) trackPoints.get(5) )[0]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号