Java: A two dimensional array is stored in column-major or row-major order?

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.

Leave a Comment