数组三者区别:
数组(datatype[ ]):存储的类型单一,且不能动态增加。
集合(ArrayList):可以存储多种类型元素,还可以动态增加,但极大消耗资源。
泛型集合(List):存储的类型单一,但可以动态增加。
数组在声明时,必须指定其存储类型,并且直接或间接分配内存空间,因此不能实现动态增加。
数组的声明有4种,以【int】类型举例:int[] aArray = new int[3];//声明一个整型数组,并使用 new 关键字为其分配3个内存空间
int[] bArray = new int[3] { 1, 2, 3 };
//后面两种比较常用
int[] cArray = new int[] { 1, 2, 3 };
int[] dArray = { 1, 2, 3 };
数组的长度:
int[] myArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine(myArray.Length);//数组的长度,输出:10
数组的赋值与取值:
int[] myArray = new int[10]; myArray[0] = 1;//数组下标从0开始 int temp = myArray[1]; Console.WriteLine(temp);//整型数组元素默认为0,输出:0 Console.ReadKey();集合
声明集合(ArrayList)要先引用System.Collections命名空间。集合在声明时,无需指定其存储类型。其内存空间也会随着集合中的元素增加而变大。因此,非常适合用来存储不同类型的元素。但在实际开发过程,十分消耗内存,所以显得十分鸡肋。
集合的声明:ArrayList list = new ArrayList();集合元素的添加:
ArrayList list = new ArrayList();
list.Add(1);//存储整数类型
list.Add('1');//存储字符类型
list.Add("1");//存储字符串类型
list.Add(true);//存储布尔类型
list.Add(list);//存储集合类型
list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });//依次存储整型数组的每个元素
list.AddRange(new char[] { 'a', 'b', 'c' });//依次存储字符数组的每个元素
//存储各种类型...
注意:【Add】方法的参数类型是 Object ,每次添加值类型元素就避免不了发生装箱行为,因此也十分消耗内存。
集合元素个数与可存储空间(可变):ArrayList list = new ArrayList();
list.Add(1);
Console.WriteLine(list.Count);//集合元素个数,输出:1
Console.WriteLine(list.Capacity);//集合可存储空间,输出:4
//添加更多的集合元素,当元素个数超出可存储空间时,可存储空间翻倍增长
list.Add(1);
list.Add("c");
list.Add('c');
list.Add(true);
Console.WriteLine(list.Count);//集合元素个数,输出:5
Console.WriteLine(list.Capacity);//集合可存储空间,输出:8
集合可存储空间增长规律:4(默认)、8、16、32、64、128、256、512 … …
集合的重新赋值与取值:ArrayList list = new ArrayList(); list.Add(2);//添加的元素会自动补充到前面 Console.WriteLine(list[0]);//输出:2 list[0] = 1; Console.WriteLine(list[0]);//输出:1
注意:集合元素必须在【Add】之后,才能对某个位置的元素进行重新赋值,否则会报错。
泛型集合泛型集合(List
List泛型集合元素的添加:list = new List ();
Listlist = new List (); list.Add(1); list.Add(2); list.Add(3); list.AddRange(new int[] { 1, 2, 3}); //只能存储int类型
注意:与集合不同的是,泛型集合【Add】方法的参数类型是指定的类型【T】。因此就避免了装箱和拆箱的行为。
泛型集合元素个数与可存储空间(可变):Listlist = new List (); list.Add(1); Console.WriteLine(list.Count);//泛型集合元素个数,输出:1 Console.WriteLine(list.Capacity);//泛型集合可存储空间,输出:4 //添加更多的整数类型元素,当元素个数超出可存储空间时,可存储空间翻倍增长 list.Add(1); list.Add(1); list.Add(1); list.Add(1); Console.WriteLine(list.Count);//泛型集合元素个数,输出:5 Console.WriteLine(list.Capacity);//泛型集合元素个数,输出:8
泛型集合与集合相同,它们的可存储空间增长规律一致。
泛型集合的重新赋值与取值:Listlist = new List (); list.Add(2);//添加的元素会自动补充到前面 Console.WriteLine(list[0]);//输出:2 list[0] = 1; Console.WriteLine(list[0]);//输出:1
注意:泛型集合与集合相同,泛型集合的元素必须在【Add】之后,才能对某个位置的元素进行重新赋值,否则会报错。
比较泛型集合与数组、集合的特点: 1、泛型集合与数组都只能存储相同类型的元素,但泛型集合可实现动态增加。 2、泛型集合与集合都可以动态增加,但泛型集合只能添加指定的类型元素。 3、泛型集合添加元素不会发生装箱行为,而集合添加元素会发生装箱行为。 4、未发生装箱行为的泛型集合比发生装箱行为的集合,更节省内存资源。
因为作者精力有限,文章中难免出现一些错漏,敬请广大专家和网友批评、指正。



