class Program { static void Main(string[] args) { ArrayList a = new ArrayList();//集合类型为object List<int> li=new List<int>();//集合类型不确定 Stopwatch sw1 = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); sw1.Start(); for (int i = 0; i < 100000; i++)//该循环需要是的时间明显长 { a.Add(i);//因为ArrayList是object类型.需要将object类型转换为int类型 } sw1.Stop(); Console.WriteLine(sw1.Elapsed); sw1.Start(); for (int i = 0; i < 100000; i++)//该循环需要的时间明显短 { li.Add(i); } sw2.Stop(); Console.WriteLine(sw2.Elapsed); //如果处理的是一个类比如Person类,泛型集合仍然课表现出较好的效率 Hashtable h = new Hashtable(); Dictionary<string,Person> d=new Dictionary<string,Person>(); Person p1=new Person("翟群",16); Person p2=new Person("何雄军",24); d.Add(p1.Name,p1); d.Add(p2.Name,p2); //p2与d["何雄军"]都可以访问到p2对象 Console.ReadKey(); } } class Person { private string name; public string Name { set { name =value; } get { return name; } } private int age; public int Age { get { return age; } } public void SayHello() { Console.WriteLine("我叫{0},我今年{1}岁了"); } public Person(string name,int age) { this.name = name; this.age = age; } }
class Program { static void Main(string[] args) { ArrayList a = new ArrayList();//集合类型为object List<int> li=new List<int>();//集合类型不确定 Stopwatch sw1 = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); sw1.Start(); for (int i = 0; i < 100000; i++)//该循环需要是的时间明显长 { a.Add(i);//因为ArrayList是object类型.需要将object类型转换为int类型 } sw1.Stop(); Console.WriteLine(sw1.Elapsed); sw1.Start(); for (int i = 0; i < 100000; i++)//该循环需要的时间明显短 { li.Add(i); } sw2.Stop(); Console.WriteLine(sw2.Elapsed); //如果处理的是一个类比如Person类,泛型集合仍然课表现出较好的效率 Hashtable h = new Hashtable(); Dictionary<string,Person> d=new Dictionary<string,Person>(); Person p1=new Person("翟群",16); Person p2=new Person("何雄军",24); d.Add(p1.Name,p1); d.Add(p2.Name,p2); //p2与d["何雄军"]都可以访问到p2对象 Console.ReadKey(); } } class Person { private string name; public string Name { set { name =value; } get { return name; } } private int age; public int Age { get { return age; } } public void SayHello() { Console.WriteLine("我叫{0},我今年{1}岁了"); } public Person(string name,int age) { this.name = name; this.age = age; } }