Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between these blocks of code?

So I went over this block of code several times in a book that I'm reading:

int[][] someArray = new int[size][];
for(int i=0; i<size; i++)
   someArray[i] = new int[size];

I don't see any difference between that and the following declaration:

int[][] someArray = new int[size][size];

Did I miss anything here? Is there any reason why I should use the long block of code above?

Thanks,

like image 781
chepukha Avatar asked Nov 08 '11 02:11

chepukha


Video Answer


2 Answers

You can create ragged or jagged arrays with the first construct

like image 51
parapura rajkumar Avatar answered Sep 29 '22 20:09

parapura rajkumar


As said by parapura you can create what's called a ragged array. Essentially you can make something triangular shaped and such (might resemble stairs or a christmas tree or whatever you want it to be). So it can be like (using random numbers)

1 2 3

1 2

4 4 5 6 2 3 5

4 5 1

2 2 5 2

where the lengths of the sub arrays are different sizes. In your example though they are both the same size so both ways do exactly the same thing.

One reason this could be done is to save space in memory instead of zero filling empty slots.

like image 41
Jesus Ramos Avatar answered Sep 29 '22 21:09

Jesus Ramos