I always get confused why does the 2D array in Java has a strict requirement for declaring the size of the row but not the column, this confuses further with 3D and 4D arrays.
// Invalid, 2D array with no row and no column?
int[][] arr = new int[][];
// Valid, 2D array of size 2X3
int[][] arr = new int[2][3];
// Valid, column size is not specified, size of 2D array?
int[][] arr = new int[2][];
// Valid, column size is not specified, size of 3D array?
int[][][] arr = new int[2][][];
It allows you to delay decision regarding the number of columns, as well as define a different number of columns for different rows.
For example:
int [][] arr = new int[2][];
arr[0] = new int[5];
arr[1] = new int[3];
The first row of the array has 5 columns, but the second row has only 3 columns. This is not possible if you specify the number of columns when you declare the 2D array.
It may become less confusing is you think of a multi-dimensional array as a 1 dimensional array whose elements are themselves arrays of a lower dimension.
So a 2 dimensional int array (int[][]
) is a 1 dimensional array whose elements are int
arrays (int[]
).
You can instantiate this array by specifying the number of elements:
int[][] arr = new int[2][];
which gives you an array of two int[]
elements, where the 2
elements are initialized to null
.
This is similar to initializing an array of some reference type:
Object[] arr = new Object[2];
which gives you an array of two Object
elements, where the 2
elements are initialized to null
.
The new int[2][3]
instantiation is actually the special case - since it instantiates both the outer array (the one having 2 elements) and the inner arrays (each having 3 elements), which are the elements of the outer array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With