Click to enter _ more _java thousand ask
1. What is the difference between an array and a reference variable of a normal object?
Learn what an array looks here: What is an array in Java
For an array of Java, only type-compatible (that is, the same data-type system and adherence to the low-to-high principle) can pass an array reference to another array reference, but still cannot change the array length (just the point of adjusting the pointer to the array reference).
Understanding Array Passing look here: how arrays are passed
Public classTestarraylength { Public Static void Main(string[] args) {int[] numbers = {3,5, A};int[] digits =New int[4]; System. out. println ("digits array length:"+ digits.length);//4 for(intNumber:numbers) {System. out. Print (number +",");//3,5,12,} System. out. println (""); for(intdigit:digits) {System. out. print (digit +",");//0,0,0,0,} System. out. println (""); digits = numbers; System. out. println ("digits array length:"+ digits.length);//3}}
The results of the implementation are as follows:
Digits Array Length: 4
3,5,12,
0,0,0,0,
Digits Array Length: 3
After the array is initialized in memory for example, there are 2 new array objects in the heap, and there are 2 reference variables in the stack that point to the two array objects respectively:
After performing digits = numbers assignment, although the seemingly digits array length appears to be 4 to 3, it is only numbers and digits pointing to the same array object.
The digits itself loses its reference and becomes garbage, waiting for garbage collection to be recycled (but its length is still 4).
See Java garbage collection here: What is the Java garbage collection mechanism
This article will make it clear how the array is stored in memory: How the Java array is stored in memory
Java thousands ask _06 data structure (015) _ array and ordinary object reference variable what is the difference