In Java, is a multidimensional array stored in column-major or row-major order?
Java actually stores two-dimensional arrays as arrays of arrays. Each element of the outer array has a reference to each inner array. The picture below shows a 2D array that has 3 rows and 7 columns. Notice that the array indices start at 0 and end at the length - 1.
Arrays in Java can store many items of the same type. You can even store items in two-dimensional (2D) arrays which are arrays that have both rows and columns. A row has horizontal elements. A column has vertical elements.
Java specifies arrays similar to that of a "row major" configuration, meaning that it indexes rows first. This is because a 2D array is an "array of arrays".
A 2D array is stored in the computer's memory one row following another. The address of the first byte of memory is considered as the memory location of the entire 2D array.
Java doesn't have multi-dimensional arrays. It has arrays of arrays. So for instance,
int[][]
...is an array of int[]
(and of course int[]
is an array of int
).
Consequently, Java is neither column-major nor row-major order (but see note below about how to read a[2][3]
), because while a given array's entries are stored in a contiguous block of memory, the subordinate arrays those entries point to are object references to completely separate, unrelated blocks of memory. This also means that Java's arrays of arrays are inherently jagged: The entry at [0]
might refer to a 3-slot array, the one at [1]
might refer to a 4-slot array, [2]
might not refer to an array at all (it could have null
), and perhaps [3]
refers to a 6-slot array.
A picture is worth 1k-24 words and all that:
+−−−−−−−−+ +−−−−>| int[] | +−−−−−−−−−−−+ | +−−−−−−−−+ | int[][] | | | 0: int | +−−−−−−−−−−−+ | | 1: int | | 0: int[] |−−−−−−+ | 2: int | | 1: int[] |−−−−−−+ +−−−−−−−−+ | 2: null | | | 3: int[] |−−+ | +−−−−−−−−+ +−−−−−−−−−−−+ | +−−−−>| int[] | | +−−−−−−−−+ | | 0: int | | | 1: int | | | 2: int | | | 3: int | | +−−−−−−−−+ | | +−−−−−−−−+ +−−−−−−−−−| int[] | +−−−−−−−−+ | 0: int | | 1: int | | 2: int | | 3: int | | 4: int | | 5: int | +−−−−−−−−+
Once you know that, you know that (say) a[2][3]
means "Get the array referenced by the entry at index 2
of a
, then get the entry referenced by index 3
of that subordinate array." I think of it as fairly similar to row-major order, but it's not quite the same thing.
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