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

前端 未结 3 2081
轻奢々
轻奢々 2020-11-29 02:39

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

3条回答
  •  鱼传尺愫
    2020-11-29 03:25

    Neither. What we may sometimes think of as two-dimensional array in Java is actually an array of references to arrays. It's not stored linearly in memory.

    The Java Language specification notes this in the introduction:

    The language supports arrays of arrays, rather than multidimensional arrays.

    This has several implications.

    • Arrays of arrays can be jagged -- member arrays can have different lengths.
    • The members of an outer array are references, and can be null.
    • Cloning an outer array is shallow -- the member arrays are shared between the original and the clone.

    From the JLS, section 10.2, "Array Variables":

    A single variable of array type may contain references to arrays of different lengths, because an array's length is not part of its type.

    From the JLS, section 10.7, "Array Members":

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

提交回复
热议问题