0

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 arrays in it?

Thank you for your help!

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The last can be abbreviated println(((int[]) trackPoints.get(5))[0]);. It saves a line and a temp variable, but the two-line version is a bit easier to read.
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.