c#的List,
list
泛型集合,可以取代ArrayList
常用方法
List<int> list = new List<int>();
| 方法名 |
作用 |
| Add() |
添加元素 |
| AddRange |
添加一個集合 |
| ToArray() |
將集合轉數組 |
數組有個方法叫ToList(),可以將數組轉成集合;
為什麼用list 而不是ArrayList
裝箱與拆箱
把實值型別轉換為為參考型別叫裝箱,把參考型別轉換為實值型別稱為拆箱;
裝箱和拆箱會是運行時的操作,會使程式已耗用時間長,而使用泛型集合在編譯的時候產生的是指定的類型;
看兩種類型是否發生了裝箱或者拆箱,要看,這兩種類型是否存在繼承關係,有繼承關係才有可能發生裝箱操作;
| 類名 |
元素類型 |
是否發生拆裝箱 |
已耗用時間 |
| list |
確定且唯一 |
否 |
比較短 |
| ArrayList |
不確定,可有很多種 |
是 |
時間長 |
using System;using System.Collections;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading.Tasks;namespace List泛型集合{ class Program { static void Main(string[] args) { ArrayList list = new ArrayList(); //ArrayList 程式用時:00:00:00.1229805 //list 程式用時:00:00:00.0276141 //List<int> list = new List<int>(); list.Add(0); list.Add(0); Console.WriteLine(list.Count); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { list.Add(i); } sw.Stop(); Console.WriteLine("程式用時:"+sw.Elapsed); Console.ReadKey(); } }}