How to insert values in two dimensional array programmatically?

后端 未结 6 1396
栀梦
栀梦 2020-12-10 15:48

I want to do this dynamically in java. I know how to insert values in single dimensional array. I am bit confused in two dimensional array.

static final Str         


        
6条回答
  •  难免孤独
    2020-12-10 16:16

    You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

    If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

    But you can chain the index operator for array element access.

    String[][] x = new String[2][];
    x[0] = new String[1];
    x[1] = new String[2];
    
    x[0][0] = "a1";
        // No x[0][1] available
    x[1][0] = "b1";
    x[1][1] = "b2";
    

    Note the dimensions of the child arrays don't need to match.

提交回复
热议问题