Click to enter _ more _java thousand ask
1. How to store the basic type array in memory
A reference type can be stored in an array of java.
Storing the reference type's memory distribution is relatively complex compared to storing the base type. Consider a program that stores the basic types:
Learn what an array looks here: What is an array in Java
Learn how arrays are stored in memory look here: How the Java array is stored in memory
publicclass TestPrimitiveArray { publicstaticvoidmain(String[] args) { //1.定义数组 int[] numbers; //2.分配内存空间 newint[4]; //3.为数组元素指定值 for(int1;i <= numbers.length;i++) { numbers[i] = i ; } }}
Memory distribution
It can be seen that the array elements are stored directly in the heap memory, while manipulating the array elements is actually a variable that operates on the underlying type.
2. How to store the array of reference types in memory
Let's take a look at an instance of storing an array of reference types:
Class Person { Public intAge PublicString name; Public void Display() {System. out. println (name +"The Age is:"+ age); }} Public classTestreferencearray { Public Static void Main(string[] args) {//1. Defining Arraysperson[] persons;//2. Allocating memory SpacePersons =Newperson[2];//3. Specifying values for an array elementperson P1 =NewPerson (); P1.age = -; P1.name ="Miracle"; person P2 =NewPerson (); P2.age = -; P2.name ="Miracle He"; persons[0] = P1; persons[1] = P2;//The value of the output element for(Person P:persons) {P.display (); } }}
The element is an array of reference types, and the storage in memory is completely different from the base type.
At this point the array element holds the reference, pointing to another piece of memory where valid data is stored.
Understanding reference variables for arrays and ordinary objects: what is the difference between an array and a reference variable of a normal object
Java thousands ask _06 data structure (016) _ Reference type array in memory how to store