where is array saved in memory in java?

后端 未结 4 2251
半阙折子戏
半阙折子戏 2021-01-04 08:19

If I have a function that in that function I declare:

Object arr[] = new Object[20];

Where are arr and the whole array stored? heap? stack?

4条回答
  •  抹茶落季
    2021-01-04 09:13

    In Java, basically any time you use the new keyword you are allocating space on the heap for an object to be stored.

    The variable you use to point to that object contains a reference stored on the stack.

    So for example:

                                        // This array object is
                                        // stored on the heap.
    String[] arr                      = new String[5];
    // This reference (arr) is stored
    // in a variable on the stack.
    

    In the case of an array of reference types like an Object[], the space allocated is a contiguous block large enough to store however many references the array will hold. Any particular reference, such as the one at arr[0], will itself point to another location on the heap where the individual object is stored.

    The array, somewhere on the heap:
    [a*][b*][  ][  ][  ]
    
    a (elsewhere on the heap):
    "abc"
    
    b (yet another heap location):
    [A List object]
    

    The only exception to this is with arrays of primitives, like int[]: in this case the array itself is still a contiguous block on the heap, but each position within the array contains the actual value itself rather than a reference to another position on the heap.

提交回复
热议问题