C#学习笔记之——List和ArrayList

using System;
using System.Collections.Generic;
using System.Collections;
public static class MathMethod
	{
		public static void Print<T> (List<T> list) {
			foreach (T each in list) {
				Console.Write ("{0} ", each);
			}
			Console.WriteLine ();
		}
	}

	class MainClass
	{
		public static void Main (string[] args)
		{
			//泛型集合List
			List<int> myList = new List<int> ();

			myList.Add (22);//添加元素22
			myList.Add(1);
			myList.Add (45);
			myList.Add (100);
			//遍历输出
			MathMethod.Print(myList);

			//集合中插入元素
			myList.Insert(2,33);
			MathMethod.Print (myList);

			Console.WriteLine (myList.Contains (2));//判断某个元素是否存在

			myList.Reverse ();//将整个列反转
			MathMethod.Print(myList);

			myList.Remove (22);//删除元素
			MathMethod.Print (myList);

			myList.Clear ();//整个list清除
			MathMethod.Print (myList);
			Console.WriteLine ("---------");
		}
	}

List类是ArrayList类的泛型等效类

• 同样继承 IList接口 ,IEnumrator接口 和ICollection

IList<T>接口用于可通过位置访问其中的元素列表,这个接口定义了一个索引 ,可以在集合指定位置插入或删除某些项.IList<T>接口派生自ICollection<T>接口

这个接口定义了方法GetEnumerator(),返回一个实现了IEnumerator接口的枚举.如果将foreach语句用于集合,就需要实现该接口

ICollection<T>接口由泛型集合类实现.使用这个接口可以获取集合中的元素个数(count),把集合复制到数组中(CopyTo()),还可以添加和删除元素

• 与ArrayList 相同的是,声明集合时需要声明集合内部的数据类型,即T的类型.

• 安全的集合类型
• 某种情况时,在处理值类型时其处理速度 ArrayList快的多

数组,ArrayList和List的区别:

  1. ArrayList存在不安全类型(ArrayList会把所有插入其中的数据都当做Object来处理)
装箱拆箱的操作,增加对内存的消耗,List是泛型,可以指定特定的类型,避免过多的装箱拆箱操作,减少增加对内存的消耗。
  2. 数组在声明时必须指定长度,而其他两个不需要。
  3. 数组插入数据很麻烦,而另外两种很容易。
  4. ArrayList可以插入不同类型数据,而其他两种只能插入特定类型数据。
  5. 数组可以是多维度,而另外两种只能是单维度。
原文地址:https://www.cnblogs.com/AlinaL/p/12852183.html