Java array drill down
Java array drill down
Array in memory
As mentioned earlier, array is a reference type, and array reference variable is only a reference. When it points to effective memory, array elements can be accessed through array variables, that is, array variables and array elements are open in memory.
It can be understood that a person's name is a reference variable. Finding this person through this person's name and obtaining all his information is the process of accessing its real object through the reference variable.
So, where are these two things in memory?
Heap and stack in Java
So: to make an array completely "garbage", directly assign the array variable null.
As follows:
int[]arr = new int[3];
arr = null;
arr[1]=0;//java.lang.NullPointerException
The specific garbage collection mechanism in Java will be summarized later and will be supplemented..
Basic type initialization
For basic arrays, the values of array elements are stored directly in the corresponding array elements. Therefore, when initializing the array, first allocate memory space for the array, and then directly put the value of the array element in the corresponding position.
public class Test1
{
public static void main(String[] args)
{
//定义一个int[]类型的数组变量
int[] arr;
//动态初始化数组,整型默认为0
arr = new int[4];
//利用for循环给数组每个元素赋值
for(int i = 0;i<arr.length;i++) arr[i]=i;
//打印显示数组结果
for(int i:arr) System.out.print(i+" ");//0 1 2 3
}
}
Initialization of reference type array
Hey, the array itself is a reference type, and the created array element is a reference type. The array element also points to another piece of memory, where valid data is loaded.
We know that class is one of the reference types, so let's create an array of all classes. We should start learning and summarizing about arrays soon, so let's talk about it briefly first and need to be supplemented.
class Hero
{
public int defenseVal;
public int attackVal;
}
public class Test
{
public static void main(String[] args)
{
//定义一个students数组变量,其类型是Hero[]
Hero[] heros;
//动态初始化
heros = new Hero[2];
//创建一个Hero实例,并让Zed变量指向该实例
Hero Zed = new Hero();
//为Zed赋攻击力和防御力属性
Zed.attackVal = 95;
Zed.defenseVal = 5;
//让数组的第一个元素指向实例Zed
heros[0]=Zed;
//发现Zed和heros[0]指向同一片内存。
System.out.println(heros[0].attackVal==Zed.attackVal);
}
}