1

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

ArrayList[][][] 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 (the IDE I'm using unfortunately doesn't give me a very good error message).

What's the proper way to create an integer ArrayList?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Tomek
  • 4,689
  • 15
  • 44
  • 52
  • 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 02 '10 at 05:37
  • Just write `new Integer(77)` instead of the `int` literal. – joschi Nov 02 '10 at 07:18
  • No, write `Integer.valueOf(77)`. – 2rs2ts Mar 27 '14 at 22:13

5 Answers5

10

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.

joschi
  • 12,746
  • 4
  • 44
  • 50
4

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);
  }
}
rjmoggach
  • 1,458
  • 15
  • 27
3

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.

Andy Dvorak
  • 491
  • 6
  • 11
2

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>();.

EboMike
  • 76,846
  • 14
  • 164
  • 167
1

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.

Andy White
  • 86,444
  • 48
  • 176
  • 211