Why is declaring an empty array of non-empty array(s) legal in Java?
An int[][]
array is an array whose elements are int[]
(i.e. its elements are arrays of int
).
Just like you are allowed to define an empty array of int
elements:
int[] empty = new int[0];
or an empty array of String
elements:
String[] empty = new String[0];
You are also allowed to define an empty array of int[1]
elements:
int[][] empty = new int[0][1];
Perhaps it's the syntax that is somewhat confusing here.
If it was
int[][] empty = new (int[1])[0]
it would be clearer that you are defining an empty array whose element type is int[1]
.
However, since the number in the first square brackets represents the number of elements in the outer array, new int[1][0]
does not represent an empty array, but an array of a single element (whose single element is an empty int
array).