Initialising a multidimensional array in Java

前端 未结 8 878
小鲜肉
小鲜肉 2020-11-22 14:20

What is the correct way to declare a multidimensional array and assign values to it?

This is what I have:

int x = 5;
int y = 5;

String[][] myStringA         


        
8条回答
  •  囚心锁ツ
    2020-11-22 14:46

    Java doesn't have "true" multidimensional arrays.

    For example, arr[i][j][k] is equivalent to ((arr[i])[j])[k]. In other words, arr is simply an array, of arrays, of arrays.

    So, if you know how arrays work, you know how multidimensional arrays work!


    Declaration:

    int[][][] threeDimArr = new int[4][5][6];
    

    or, with initialization:

    int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
    

    Access:

    int x = threeDimArr[1][0][1];
    

    or

    int[][] row = threeDimArr[1];
    

    String representation:

    Arrays.deepToString(threeDimArr);
    

    yields

    "[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"
    

    Useful articles

    • Java: Initializing a multidimensional array
    • Java: Matrices and Multidimensional Arrays

提交回复
热议问题