Reputation: 15
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
Reputation: 64
Creates an array of 2 int
arrays, which are of length 3, which are filled with 0
s.
| [ ][0] | [ ][1] | [ ][2]
[0][ ] | 0 | 0 | 0
[1][ ] | 0 | 0 | 0
Creates a "jagged" array containing { 11, 13 }
, and { 13, 14, 15 }
. And which contained values are themselves array of int
s.
| [ ][0] | [ ][1] | [ ][2]
[0][ ] | 11 | 12 | error
[1][ ] | 13 | 14 | 15
Upvotes: 1
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