Skip to content
Advertisement

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}})

Advertisement

Answer

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);
  }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement