简体   繁体   中英

Size of 2d array in Java

I defined a 2d array in Java. As I read about it(ie 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.

For every one dimensional array you have a 24 byte overhead in addition to the space for the data in the array.

  • So your first two lines of code each create an array of 10 pointers - you are right about that - which take 8 bytes each on 64-bit system. This means you are allocating 2 * (24 + 10 * 8) = 208 bytes.
  • In the first 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.
  • In the second loop, you are not allocating any new memory.
  • In total you are using 208 + 480 = 688 bytes.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM