Is an
ArrayList<ArrayList<Integer>> numbers; like a 2D array of ints int[][] numbers;?
Or are these stored completely different from one another?
-
2Apart that the first one can grow dynamically, both are similars.Alex– Alex2012-11-30 08:03:02 +00:00Commented Nov 30, 2012 at 8:03
-
both are dissimilar in memory allocationNarendra Pathai– Narendra Pathai2012-11-30 08:14:03 +00:00Commented Nov 30, 2012 at 8:14
3 Answers
It is a structure with two dimensions, so it is [][]-like, yet there is one very important difference: if you allocate a two-dimensional array in one step you'll get same size in the second dimension for all elements of the first dimension:
int[][] arrayOfInts = new int[5][4];
for (int[] second : arrayOfInts) {
System.out.println(second.length);
}
prints 5 times a "4".
Using ArrayList of ArrayLists all elements of the second dimension may have different size.
As pointed out by jlordo: an array of ints may also have the second dimension of different lengths if it is created dynamically:
int[][] anotherArray = new int[5][];
for (int i=0; i<5; i++) {
anotherArray[i] = new int[i];
}
in which case a NullPointerException can be throws if the second dimension were accessed before being intialized, like:
int[][] yetAnotherArray = new int[5][];
System.out.println(yetAnotherArray[2][3]);
The other difference: after allocating a int[x][y] the memory for all its elements in both dimension is allocated from the very first moment. In ArrayList of ArrayLists the memory needed for the lists is allocated, but the memory needed for its elements will be used not before you create their content. So a similar code as before will print nothing, because at the beginning there will not be even a single element in the first ArrayList.
In order to have the second dimension you first have to create all ArrayLists of the second dimension:
ArrayList<ArrayList<Integer>> arrayOfArrays = new ArrayList<ArrayList<Integer>>();
for (int i=0; i < 5; i++) {
arrayOfArrays.add(new ArrayList<Integer>();
}
Further on the accessing side:
int[][] arrayOfInts = new int[5][4];
System.out.println(arrayOfInts[2][3]);
prints 0 because all of the memory is already allocated. The access is safe both in addressing the dimensions and its value, because it is of a primitive type.
ArrayList<ArrayList<Integer>> arrayOfArrays = new ArrayList<ArrayList<Integer>>();
for (int i=0; i < 5; i++) {
arrayOfArrays.add(new ArrayList<Integer>();
}
System.out.println(first.get(2).get(3));
throws ArrayOutOfBoundsException. You have to check the size of the elements before accessing them.
Now there is also one important difference between int[][] and Integer[][]: primitive types always have values, so after allocating int[4][5] you'll have 0 for unitialized elements. Integer[4][5] contain objects, so unitialized elements will have null instead.
7 Comments
int[][] with different sizes in second dimension.int[][].int[][] a = new int[3][]; a[1][1] = 7;