Which comes first in a 2D array, rows or columns?

前端 未结 9 734
小鲜肉
小鲜肉 2020-12-07 12:53

When creating a 2D array, how does one remember whether rows or columns are specified first?

9条回答
  •  忘掉有多难
    2020-12-07 13:46

    Java is considered "row major", meaning that it does rows first. This is because a 2D array is an "array of arrays".

    For example:

    int[ ][ ] a = new int[2][4];  // Two rows and four columns.
    
    a[0][0] a[0][1] a[0][2] a[0][3]
    
    a[1][0] a[1][1] a[1][2] a[1][3]
    

    It can also be visualized more like this:

    a[0] ->  [0] [1] [2] [3]
    a[1] ->  [0] [1] [2] [3]
    

    The second illustration shows the "array of arrays" aspect. The first array contains {a[0] and a[1]}, and each of those is an array containing four elements, {[0][1][2][3]}.

    TL;DR summary:

    Array[number of arrays][how many elements in each of those arrays]
    

    For more explanations, see also Arrays - 2-dimensional.

提交回复
热议问题