Initialising a multidimensional array in Java

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

    Multidimensional Array in Java

    Returning a multidimensional array

    Java does not truely support multidimensional arrays. In Java, a two-dimensional array is simply an array of arrays, a three-dimensional array is an array of arrays of arrays, a four-dimensional array is an array of arrays of arrays of arrays, and so on...

    We can define a two-dimensional array as:

    1. int[ ] num[ ] = {{1,2}, {1,2}, {1,2}, {1,2}}

    2. int[ ][ ] num = new int[4][2]

      num[0][0] = 1;
      num[0][1] = 2;
      num[1][0] = 1;
      num[1][1] = 2;
      num[2][0] = 1;
      num[2][1] = 2;
      num[3][0] = 1;
      num[3][1] = 2;
      

      If you don't allocate, let's say num[2][1], it is not initialized and then it is automatically allocated 0, that is, automatically num[2][1] = 0;

    3. Below, num1.length gives you rows.

    4. While num1[0].length gives you the number of elements related to num1[0]. Here num1[0] has related arrays num1[0][0] and num[0][1] only.

    5. Here we used a for loop which helps us to calculate num1[i].length. Here i is incremented through a loop.

      class array
      {
          static int[][] add(int[][] num1,int[][] num2)
          {
              int[][] temp = new int[num1.length][num1[0].length];
              for(int i = 0; i
                                                              
提交回复
热议问题