Initialising a multidimensional array in Java

前端 未结 8 880
小鲜肉
小鲜肉 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:50

    You can also use the following construct:

    String[][] myStringArray = new String [][] { { "X0", "Y0"},
                                                 { "X1", "Y1"},
                                                 { "X2", "Y2"},
                                                 { "X3", "Y3"},
                                                 { "X4", "Y4"} };
    
    0 讨论(0)
  • 2020-11-22 14:57

    I'll add that if you want to read the dimensions, you can do this:

    int[][][] a = new int[4][3][2];
    
    System.out.println(a.length);  // 4
    System.out.println(a[0].length); // 3
    System.out.println(a[0][0].length); //2
    

    You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length.

    0 讨论(0)
提交回复
热议问题