As far as I understand a two-dimensional array in java is an array of arrays. Analogously to the usual array notation I would expect this to mean that
int[][]
is actually
(int[])[]
(An array of int arrays). Thus I would expect the length of the array
int[][] array = new int[2][3]; // (int[2])[3]
to be 3 (as it would be an array of length 3 of arrays of length 2). It does however appear to be the other way round.
I tried to find an explanation for this, but was unable to. I found many posts explaining how to initialize multidimensional arrays and that they are arrays of arrays but I was unable to find any explanation of why the order of the indices works out this way.
My only theory is that people find it more natural to iterate over the left index first and Java is built in a way such that this operation is more efficient so the developers made this choice very deliberately.
I am thankful for any source confirming this interpretation or any other reasons why it works out this way.
edit: Since there seems to be some confusion as to why anyone would ever believe using the indices the other way round would be a good idea, here is some clarification:
For a type T
the expression new T[5]
usually yields an array of size 5. The type int[]
seems to be a perfectly good type, however Java does not allow me to say new (int[])[5]
and instead forces me to initiate this array of arrays using new int[5][]
. I was looking for a reason why Java would do that to me (and got one).
One other thing I would like to add with respect to the (very good) answers for anyone thinking like me: In a world where nobody had ever thought about two-dimensional arrays and you were allowed to create arrays of type int[]
as you would create any other array, the following might be perfectly legal code.
int[][] = new (int[])[5];
int[] firstArray = new int[3];
int[0] = firstArray;
int[0][2] = 1; // last element of first array
int[0][4] = 2; // IndexOutOfBoundsException, trying to access 5th element of firstArray
This would of course be utterly confusing so I am glad that multidimensional arrays get a special treatment.