Java Uneven Multidimensional array

3.8k Views Asked by At

I came by this piece of code and I'm not sure what is exactly happening. It's as follows:

       int twod [] [] = new int[4][];// i know the first one is row

       twod [0]  = new int[1];//
       twod [1]  = new int[2];//  What are these? 
       twod [2]  = new int[3];//
       twod [3]  = new int[4];//

What are the last 4 lines doing?

2

There are 2 best solutions below

5
Shar1er80 On BEST ANSWER

What you posted didn't compile for me. I think this is what you want for jagged arrays.

   int twod [][] = new int[4][];// i know the first one is row

   twod[0] = new int[1];//
   twod[1] = new int[2];//  What are these? 
   twod[2] = new int[3];//
   twod[3] = new int[4];//

Results (In debug):

enter image description here

4
Turing85 On

The above code does not compile. But I have a strong feeling OP meants something like this:

   int twod[][] = new int[4][];// i know the first one is row

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

This creates an array of the following shape (up->down = 1st dimension, left->right= 2nd dimension):

*
**
***
****

More specific, when we query the length of the arrays, we get these results:

twod.length -> 4
twod[0].length -> 1
twod[1].length -> 2
twod[2].length -> 3
twod[3].length -> 4