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,
You can create ragged or jagged arrays with the first construct
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With