Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

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

In Java, is a multidimensional array stored in column-major or row-major order?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...