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?

3
  • 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? Commented Nov 2, 2010 at 5:37
  • Just write new Integer(77) instead of the int literal. Commented Nov 2, 2010 at 7:18
  • No, write Integer.valueOf(77). Commented Mar 27, 2014 at 22:13

5 Answers 5

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.

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

Comments

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);
  }
}

Comments

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.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.