Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Multidimensional Array in java

I am trying to understand the concept of multidimensional arrays in java. Below is the posted code.

    int [] [] [] x = new int [3] [] [];
    int i, j;
    x[0] = new int[4][];
    x[1] = new int[2][];
    x[2] = new int[5][]; 
    for (i = 0; i < x.length; i++)
     {
        for (j = 0; j < x[i].length; j++) 
         {
            x[i][j] = new int [i + j + 1];
            System.out.println("size = " + x[i][j].length);
         }
     }
     }

I do not understand what is being stored in "x[0] = new int[4][]; " and also what is the idea behind writing like that? Any suggestions would be highly helpful.

like image 468
mohan babu Avatar asked Dec 07 '25 22:12

mohan babu


2 Answers

Multidimensional array is basically an array of arrays :) Like this:

int[][] X = new int[4][3];

means:

      X[0]   X[1]   X[2]   X[3]
X -> [    ] [    ] [    ] [    ]
     [    ] [    ] [    ] [    ]
     [    ] [    ] [    ] [    ]

And

int[][] X = new int[4][];
X[0] = new int[2]; 
X[1] = new int[1]; 
X[2] = new int[3]; 
X[3] = new int[2]; 

will produce an irregular array like this:

      X[0]   X[1]   X[2]   X[3]
X -> [    ] [    ] [    ] [    ]
     [    ]        [    ] [    ]
                   [    ]       

So each of the X's "children" is another array. Simple as that, try not to overthink the concept, it is not as complex as it seems :)

like image 148
Kelevandos Avatar answered Dec 10 '25 13:12

Kelevandos


Java knows an array. The trick in java is, if you want a multidimensional array, you just create an array in an array. With x[0] = new int[4][]; you are telling that there are 4 rows in the multidimensional array, but you don't fill them. If you said new int[4][2] there would be 2 items in each row with the default value of int. If you had a language like c# you would say int[,], but this is not possible in java.

Because of this, it is also possible to put 2 items in the first row, and 3 in the next. So an uneven length is possible.

like image 39
Melvin Avatar answered Dec 10 '25 12:12

Melvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!