实在是好几天都没更新啦……找个数组内存分析来滥竽充数一下……嘿嘿……
一:声明一个int类型的数组:
int[] a ; //声明一个int类型的数组a
a = new int[5]; //为数组a分配的长度为5
内存分析如图:
过程1为声明过程,因为此时仅仅是声明,并为为其数组本身分配空间,所以在栈中分配了一块引用a的空间,其值为默认值null.
过程2为数组分配了空间,注意new int[5]的过程,也是在堆中分配了一块空间,用来存放这个长度为5的数组,但此时数组的值仍为int的初始值:0.
二:声明一个引用类型的数组:(注意与int类型的数组的区别!)
class Person //定义一个Person类
{
string name;
string gender;
int age;
Person(string name,string gender,int age)
{
this.name = name;
this.gender = gender;
this.age = age;
}
}
Person[] person; //注意此种数组与int类型数组的区别:此person数组是一个引用类型的数组!!!
person = new Person[3];
person[0] = new Person("张三","man",18);
person[1] = new Person("李四","man",19);
person[2] = new Person("狗蛋","woman",18);
内存分析如图:
引用类型的数组与int类型的数组一个最大的区别就是:引用类型的数组其数组成员是引用,而并非像int类型的数组一样装的是int值。所以
person = new Person[3];的内存执行情况是在堆中又分配了3块空间,但这3块空间内装的不是值,而是3个引用,其初始值为null.当为每一个person成员赋值一个具体的Person对象时,堆中的这3块空间中的引用才会指向自己所应该指向的那个new出来的Person对象。
(重点就是记这一句话就行:引用类型的数组中的成员装的是引用!)