简体   繁体   中英

Array of Objects Memory Allocation(Stack And Heap)

I have initialised an array of class objects, I'm curious about how they're allocated in memory(stack and heap ), I found a piece of code from a textbook, it draws the memory allocation on the left below.

My Question is: why the memory allocation is not the one I draw on the right , in the code below, new Person[]{new Person("Simon", 20)...} , the new Person object would assign its memory address to the per[0] ,however, the per[0] is created in the heap when Person[] per = new Person[3] is executed.

Initialization of an array of class objects

 class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    public class Main {
        public static void main(String[] args) {
            Person[] per = new Person[]{new Person("Simon", 20), new Person("John", 21), new Person("Willy", 22)};
        }
    }
  1. Left(TextBook)

  2. My Thought

why the memory allocation is not the one I draw on the right,

It is on the right, but if you were to use the value

per

or

per[0]

that reference would be brought onto the stack.

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