5

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,

chepukha
  • 2,371
  • 3
  • 28
  • 40

4 Answers4

6

You can create ragged or jagged arrays with the first construct

Community
  • 1
  • 1
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • +1 for mentioning ragged arrays. But in the example above, the two arrays would be arrays of identical dimensions (size * size). But imagine that in the first code snippet, you change 'someArray[i] = new int[i]'. Notice that instead of 'new int[size]', I put 'new int[i]' That's what this allows you to do, and that's a ragged array! – Zaki Saadeh Nov 08 '11 at 02:37
  • yeah, I would understand that if they give different size in the for loop but they use the same 'size'. So it doesn't make any sense to me at all.' – chepukha Nov 08 '11 at 02:39
  • You are correct. If you creating m*n array it doesn't make sense to do it the first way. I was just mentioning what the potential difference could ge – parapura rajkumar Nov 08 '11 at 11:46
2

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.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
1

No difference here. The first one is useful when we want to create arrays having different sizes.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

When in doubt take a look at the bytecode -- especially for something like this that is just a few lines of code.
Apparently the compiler has a special construct for creating the second form.

first form (without the loop): public static void main(java.lang.String[]); Code: 0: iconst_3 1: anewarray #2; //class "[I" 4: astore_1 5: return

second form:

0: iconst_3 1: iconst_3 2: multianewarray #2, 2; //class "[[I" 6: astore_1 7: return

==================

One way to look at it is that there is a LOT of wasted time in the loop when you know you are going to have a "square" array anyways. Imagine if you were at Google and you needed a two-dimensional array with size=10000000. The first form would be dramatically slower.

codeplumber
  • 469
  • 2
  • 11