Is an
ArrayList<ArrayList<Integer>> numbers; like a 2D array of ints int[][] numbers;?
Or are these stored completely different from one another?
Is an ArrayList<ArrayList<Integer>> numbers; like a 2D array of ints int[][] numbers; ? Or
Share
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:
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:
in which case a NullPointerException can be throws if the second dimension were accessed before being intialized, like:
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:
Further on the accessing side:
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.
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.