Reputation: 455
I defined a 2d array in Java. As I read about it(i.e. 2d array), the first dimension of this 2d array is a pointer (I do not know that is it right or not, please tell me about it). So If I consider it as pointer, in a 64-bit system, what will be the size of below code after execution?
short [][] array1 = new short [10][];
short[][] array2 = new short[10][];
for (int i = 0; i < 10; i++)
array1[i] = new short[1];
for (int i = 0; i < 10; i++)
array2[i] = array1[i];
Please tell me about the size of above code.
Upvotes: 1
Views: 2019
Reputation: 3325
For every one dimensional array you have a 24 byte overhead in addition to the space for the data in the array.
for
loop you are creating 10 arrays which are 24 + 2 * 10 = 44 bytes each. These are padded to at least 8 byte boundaries and thus take up 48 bytes or 480 bytes in total. Note that the actual usage depends on the JVM. For example:
In order to see the difference between outer and inner arrays it might be helpful to rewrite your code like this:
short[][] outerArray = new short[10][]; // Array of references to short arrays
short[] innerArray; // Array of shorts
for (int i = 0; i < 10; i++) {
innerArray = new short[1];
outerArray[i] = innerArray;
}
Upvotes: 2