hah hah
hah hah

Reputation: 15

What's the difference between these 2 array definitions?

What us the difference between int[][] a = new int[2][3] and int a[][] = new int[][]{{11,12},{13,14,15}}?

I decompiled the .class file and found in the first case, the JVM will use multianwearray to create the array, while in the second case, it will use anewarray.

I think in the first case, JVM will create a continuous space. Am I right?

first case (int[][] a = new int[2][3])

second case (int[][] a = new int[][]{{11,12},{13,14,15}})

Upvotes: 1

Views: 113

Answers (2)

StartsMercury
StartsMercury

Reputation: 64

First Case

Creates an array of 2 int arrays, which are of length 3, which are filled with 0s.

        | [ ][0] | [ ][1] | [ ][2] 
 [0][ ] |    0   |    0   |    0
 [1][ ] |    0   |    0   |    0

Second Case

Creates a "jagged" array containing { 11, 13 }, and { 13, 14, 15 }. And which contained values are themselves array of ints.

        | [ ][0] | [ ][1] | [ ][2] 
 [0][ ] |   11   |   12   |  error
 [1][ ] |   13   |   14   |   15

Upvotes: 1

Thomas Kläger
Thomas Kläger

Reputation: 21435

I think in the first case, jvm will create a continuous space. Am i right?

No. A multidimensional array is still an array of arrays. And it must be so, because the code that later accesses the array doesn't know how it was created.

Writing

int[][] a = new int[2][3];

allocates the same amount of heap space and the data on the heap has the same structure as if you would write

int[][] a = new int[2][];
a[0] = new int[3];
a[1] = new int[3];

except that the code for the first variant is embedded in the JVM:

https://github.com/openjdk/jdk17u/blob/master/src/hotspot/share/oops/objArrayKlass.cpp#L178 ff

objArrayOop array = allocate(length, CHECK_NULL);
//...
if (length != 0) {
  for (int index = 0; index < length; index++) {
    ArrayKlass* ak = ArrayKlass::cast(ld_klass);
    oop sub_array = ak->multi_allocate(rank-1, &sizes[1], CHECK_NULL);
    h_array->obj_at_put(index, sub_array);
  }
}

Upvotes: 1

Related Questions