Initialising a multidimensional array in Java

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

    You can declare multi dimensional arrays like :

    // 4 x 5 String arrays, all Strings are null
    // [0] -> [null,null,null,null,null]
    // [1] -> [null,null,null,null,null]
    // [2] -> [null,null,null,null,null]
    // [3] -> [null,null,null,null,null]
    
    String[][] sa1 = new String[4][5];
    for(int i = 0; i < sa1.length; i++) {           // sa1.length == 4
        for (int j = 0; j < sa1[i].length; j++) {     //sa1[i].length == 5
            sa1[i][j] = "new String value";
        }
    }
    
    
    // 5 x 0  All String arrays are null
    // [null]
    // [null]
    // [null]
    // [null]
    // [null]
    String[][] sa2 = new String[5][];
    for(int i = 0; i < sa2.length; i++) {
        String[] anon = new String[ /* your number here */];
        // or String[] anon = new String[]{"I'm", "a", "new", "array"};
        sa2[i] = anon;
    }
    
    // [0] -> ["I'm","in","the", "0th", "array"]
    // [1] -> ["I'm", "in", "another"]
    String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};
    

提交回复
热议问题