I am trying to create an array of Arraylists in Processing/Java. I have declared it in the following way.

ArrayList[][][] arrayQ;
arrayQ = new ArrayList[90][13][18];

for (int i = 0; i < 90; i++) {
      for (int j = 0; j < 13; j++) {
        for (int k = 0; k < 18; k++) {
          arrayQ[i][j][k] = new ArrayList<int>();
        }  
      } 
    }

However, adding the <int> inside the while loop throws an error. Unfortunately, I am programming with the Processing IDE and it doesn't give me a very good error that I can analyse to fix syntax problems.

Does this syntax seem correct?

Thanks,

Tomek

share|improve this question
new ArrayList<Integer>(); – Cristian Nov 2 '10 at 5:25
now what if I wanted to use the integer value and pass it to a function that takes an int? because if I try to pass it something like function(arrayQ[i][j][0].get(k), 77) it is passing this as an Integer object. how would I case it to a primitive int? – Tomek Nov 2 '10 at 5:37
Just write new Integer(77) instead of the int literal. – joschi Nov 2 '10 at 7:18
feedback

5 Answers

Here's a complete example:

ArrayList<Integer>[] foo = new ArrayList[3];

foo[0] = new ArrayList<Integer>();
foo[1] = new ArrayList<Integer>();
foo[2] = new ArrayList<Integer>();

foo[0].add(123);
foo[0].add(23);
foo[1].add(163);
foo[1].add(23789);
foo[2].add(3);
foo[2].add(2);

for (ArrayList<Integer> mylist: foo) {
  for (int bar : mylist) {
    println(bar);
  }
}
share|improve this answer
feedback

The problem is that an ArrayList requires Objects - you cannot use primitive types.

You'll need to write arrayQ[i][j][k] = new ArrayList<Integer>();.

share|improve this answer
feedback

joschi and Cristian are correct. Change new ArrayList<int>() to new ArrayList<Integer>() and you should be fine.

If at all possible, I would recommend using Eclipse as your IDE. It provides (usually) very specific, detailed, and generally helpful error messages to help you debug your code.

share|improve this answer
feedback

It looks like you're mixing the non-generic and generic ArrayLists. Your 3D array of ArrayList uses the non-generic, but you are trying to assign a generic ArrayList<int>. Try switching one of these to match the other.

share|improve this answer
feedback

Java Collections can only hold objects. int is a primitive data type and cannot be held in an ArrayList for example. You need to use Integer instead.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.