if new int[5]
creates an int array of length 5, and new String[5]
creates a String array of length 5,
then by that logic, shouldn't new int[3][4]
create an int[3] array of length 4 like {{1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}}?
if new int[5]
creates an int array of length 5, and new String[5]
creates a String array of length 5,
then by that logic, shouldn't new int[3][4]
create an int[3] array of length 4 like {{1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}}?
As phasma said, this question seems to be asking why java switches to 'column-major' during array creation and back to 'row-major' for access. It seems like multidimensional arrays in Java are allocated using a reversed intuition, but then are accessed using the 'correct' intuition.
An int[][]
should mean an array of arrays of int
, right? And it does! So when creating an array, you might be thinking like this: int[][] arr = new (int[3])[4]
. Because it should be an array of size 4 containing arrays of size 3!
However, if you were to use this intuition, you would then have to access the array like this: (arr[0-3])[0-2]
instead of (arr[0-2])[0-3]
like you had created the array, and the order would be switched and would be more confusing and hard to debug.
I believe that the reason most languages do this is to keep things consistent and to prevent confusion. You are smart to think this way, since most people would never notice.