我們用的比較多的非泛型集合類主要有 ArrayList類 和 HashTable類。我們經常用HashTable 來儲存將要寫入到資料庫或者返回的資訊,在這之間要不斷的進行類型的轉化,增加了系統裝箱和拆箱的負擔,14:31:45,例如我們需要在電子商務網站中儲存使用者的購物車資訊(商品名,對應的商品個數)時,完全可以用 Dictionary<string, int> 來儲存購物車資訊,而不需要任何的類型轉化。
1.數組是固定大小的,不能伸縮。雖然System.Array.Resize這個泛型方法可以重設數組大小,
但是該方法是重新建立新設定大小的數組,用的是舊數組的元素初始化。隨後以前的數組就廢棄!而集合卻是可變長的
2.數組要聲明元素的類型,集合類的元素類型卻是object.
3.數組可讀可寫不能聲明唯讀數組。集合類可以提供ReadOnly方法以唯讀方式使用集合。
4.數組要有整數下標才能訪問特定的元素,然而很多時候這樣的下標並不是很有用。集合也是資料列表卻不使用下標訪問。
很多時候集合有定製的下標類型,對於隊列和棧根本就不支援下標訪問!
1. 數組
int[] intArray1;
//初始化已聲明的一維數組
intArray1 = new int[3];
intArray1 = new int[3]{1,2,3};
intArray1 = new int[]{1,2,3};
2. ArrayList類對象被設計成為一個動態數群組類型,其容量會隨著需要而適當的擴充
方法
1:Add()向數組中添加一個元素,
2:Remove()刪除數組中的一個元素
3:RemoveAt(int i)刪除數組中索引值為i的元素
4:Reverse()反轉數組的元素
5:Sort()以從小到大的順序排列數組的元素
6:Clone()複製一個數組
using System; using System.Collections.Generic; using System.Text; using System.Collections; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add(100);//單個添加 foreach (int number in new int[6] { 9, 3, 7, 2, 4, 8 }) { al.Add(number);//集體添加方法一//清清月兒 } int[] number2 = new int[2] { 11,12 }; al.AddRange(number2);//集體添加方法二 al.Remove(3);//移除值為3的 al.RemoveAt(3);//移除第3個 ArrayList al2 = new ArrayList(al.GetRange(1, 3));//新ArrayList只取舊ArrayList一部份 Console.WriteLine("遍曆方法一:"); foreach (int i in al)//不要強制轉換 { Console.WriteLine(i);//遍曆方法一 } Console.WriteLine("遍曆方法二:"); for (int i = 0; i != al2.Count; i++)//數組是length { int number = (int)al2[i];//一定要強制轉換 Console.WriteLine(number);//遍曆方法二 } } } }
3. List
可通過索引訪問的對象的強型別列表。提供用於對列表進行搜尋、排序和操作的方法,在決定使用 List 還是使用 ArrayList 類(兩者具有類似的功能)時,記住 List 類在大多數情況下執行得更好並且是型別安全的。如果對 List 類的類型 T 使用參考型別,則兩個類的行為是完全相同的。但是,如果對類型 T 使用實值型別,則需要考慮實現和裝箱問題。
如果對類型 T 使用實值型別,則編譯器將特別針對該實值型別產生 List 類的實現。這意味著不必對 List 對象的列表元素進行裝箱就可以使用該元素,並且在建立大約 500 個列表元素之後,不對列表元素裝箱所節省的記憶體將大於產生該類實現所使用的記憶體。
//聲明一個List對象,只加入string參數 List<string> names = new List<string>(); names.Add("喬峰"); names.Add("歐陽峰"); names.Add("馬蜂"); //遍曆List foreach (string name in names) { Console.WriteLine(name); } //向List中插入元素 names.Insert(2, "張三峰"); //移除指定元素 names.Remove("馬蜂");
4. Dictionary
表示鍵和值的集合。Dictionary遍曆輸出的順序,就是加入的順序,這點與Hashtable不同
Dictionary<string, string> myDic = new Dictionary<string, string>(); myDic.Add("aaa", "111"); myDic.Add("bbb", "222"); myDic.Add("ccc", "333"); myDic.Add("ddd", "444"); //如果添加已經存在的鍵,add方法會拋出異常 try { myDic.Add("ddd","ddd"); } catch (ArgumentException ex) { Console.WriteLine("此鍵已經存在:" + ex.Message); } //解決add()異常的方法是用ContainsKey()方法來判斷鍵是否存在 if (!myDic.ContainsKey("ddd")) { myDic.Add("ddd", "ddd"); } else { Console.WriteLine("此鍵已經存在:"); } //而使用索引器來負值時,如果建已經存在,就會修改已有的鍵的索引值,而不會拋出異常 myDic ["ddd"]="ddd"; myDic["eee"] = "555"; //使用索引器來取值時,如果鍵不存在就會引發異常 try { Console.WriteLine("不存在的鍵""fff""的索引值為:" + myDic["fff"]); } catch (KeyNotFoundException ex) { Console.WriteLine("沒有找到鍵引發異常:" + ex.Message); }
//解決上面的異常的方法是使用ContarnsKey() 來判斷時候存在鍵,如果經常要取健值得化最好用 TryGetValue方法來擷取集合中的對應索引值
string value = ""; if (myDic.TryGetValue("fff", out value)) { Console.WriteLine("不存在的鍵""fff""的索引值為:" + value ); } else { Console.WriteLine("沒有找到對應鍵的索引值"); } //下面用foreach 來遍曆索引值對 //泛型結構體 用來儲存健值對 foreach (KeyValuePair<string, string> kvp in myDic) { Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value); } //擷取值得集合 foreach (string s in myDic.Values) { Console.WriteLine("value={0}", s); } //擷取值得另一種方式 Dictionary<string, string>.ValueCollection values = myDic.Values; foreach (string s in values) { Console.WriteLine("value={0}", s); }
常用的屬性和方法如下
常用屬性
屬性說明
Comparer
擷取用於確定字典中的鍵是否相等的 IEqualityComparer。
Count
擷取包含在 Dictionary中的鍵/值對的數目。
Item
擷取或設定與指定的鍵相關聯的值。
Keys
擷取包含 Dictionary中的鍵的集合。
Values
擷取包含 Dictionary中的值的集合。
常用的方法
方法說明
Add
將指定的鍵和值添加到字典中。
Clear
從 Dictionary中移除所有的鍵和值。
ContainsKey
確定 Dictionary是否包含指定的鍵。
ContainsValue
確定 Dictionary是否包含特定值。
Equals
已重載。 確定兩個 Object執行個體是否相等。 (從 Object繼承。)
GetEnumerator
返回逐一查看 Dictionary的枚舉數。
GetHashCode
用作特定類型的雜湊函數。GetHashCode適合在雜湊演算法和資料結構(如雜湊表)中使用。 (從 Object繼承。)
GetObjectData
實現 System.Runtime.Serialization.ISerializable介面,並返回序列化 Dictionary執行個體所需的資料。
GetType
擷取當前執行個體的 Type。 (從 Object繼承。)
OnDeserialization
實現 System.Runtime.Serialization.ISerializable介面,並在完成還原序列化之後引發還原序列化事件。
ReferenceEquals
確定指定的 Object執行個體是否是相同的執行個體。 (從 Object繼承。)
Remove
從 Dictionary中移除所指定的鍵的值。
ToString
返回表示當前 Object的 String。 (從 Object繼承。)
TryGetValue
擷取與指定的鍵相關聯的值。
5. SortedList類
與雜湊表類似,區別在於SortedList中的Key數組排好序的
//SortedList System.Collections.SortedList list=new System.Collections.SortedList(); list.Add("key2",2); list.Add("key1",1); for(int i=0;i<list.Count;i++) { System.Console.WriteLine(list.GetKey(i)); }
6.Hashtable類
雜湊表,名-值對。類似於字典(比數組更強大)。雜湊表是經過最佳化的,訪問下標的對象先散列過。如果以任意類型索引值訪問其中元素會快於其他集合。
GetHashCode()方法返回一個int型資料,使用這個鍵的值產生該int型資料。雜湊表擷取這個值最後返回一個索引,表示帶有給定散列的資料項目在字典中儲存的位置。
Hashtable 和 Dictionary <K, V> 類型
1:單線程程式中推薦使用 Dictionary, 有泛型優勢, 且讀取速度較快, 容量利用更充分.
2:多線程程式中推薦使用 Hashtable, 預設的 Hashtable 允許單線程寫入, 多線程讀取, 對 Hashtable 進一步調用 Synchronized() 方法可以獲得完全安全執行緒的類型. 而 Dictionary 非安全執行緒, 必須人為使用 lock 語句進行保護, 效率大減.
3:Dictionary 有按插入順序排列資料的特性 (注: 但當調用 Remove() 刪除過節點後順序被打亂), 因此在需要體現順序的情境中使用 Dictionary 能獲得一定方便.
HashTable中的key/value均為object類型,由包含集合元素的儲存桶組成。儲存桶是 HashTable中各元素的虛擬子組,與大多數集合中進行的搜尋和檢索相比,儲存桶可令搜尋和檢索更為便捷。每一儲存桶都與一個雜湊碼關聯,該雜湊碼是使用雜湊函數產生的並基於該元素的鍵。HashTable的優點就在於其索引的方式,速度非常快。如果以任意類型索引值訪問其中元素會快於其他集合,特別是當資料量特別大的時候,效率差別尤其大。
HashTable的應用場合有:做對象緩衝,樹遞迴演算法的替代,和各種需提升效率的場合。
//Hashtable sample System.Collections.Hashtable ht = new System.Collections.Hashtable(); //--Be careful: Keys can't be duplicated, and can't be null---- ht.Add(1, "apple"); ht.Add(2, "banana"); ht.Add(3, "orange"); //Modify item value: if(ht.ContainsKey(1)) ht[1] = "appleBad"; //The following code will return null oValue, no exception object oValue = ht[5]; //traversal 1: foreach (DictionaryEntry de in ht) { Console.WriteLine(de.Key); Console.WriteLine(de.Value); } //traversal 2: System.Collections.IDictionaryEnumerator d = ht.GetEnumerator(); while (d.MoveNext()) { Console.WriteLine("key:{0} value:{1}", d.Entry.Key, d.Entry.Value); } //Clear items ht.Clear();
Dictionary和HashTable內部實現差不多,但前者無需裝箱拆箱操作,效率略高一點。
//Dictionary sample System.Collections.Generic.Dictionary<int, string> fruits = new System.Collections.Generic.Dictionary<int, string>(); fruits.Add(1, "apple"); fruits.Add(2, "banana"); fruits.Add(3, "orange"); foreach (int i in fruits.Keys) { Console.WriteLine("key:{0} value:{1}", i, fruits); } if (fruits.ContainsKey(1)) { Console.WriteLine("contain this key."); }
HashTable是經過最佳化的,訪問下標的對象先散列過,所以內部是無序散列的,保證了高效率,也就是說,其輸出不是按照開始加入的順序,而Dictionary遍曆輸出的順序,就是加入的順序,這點與Hashtable不同。如果一定要排序HashTable輸出,只能自己實現:
//Hashtable sorting System.Collections.ArrayList akeys = new System.Collections.ArrayList(ht.Keys); //from Hashtable akeys.Sort(); //Sort by leading letter foreach (string skey in akeys) { Console.Write(skey + ":"); Console.WriteLine(ht[skey]); }
HashTable與安全執行緒:
為了保證在多線程的情況下的線程同步訪問安全,微軟提供了自動線程同步的HashTable:
如果 HashTable要允許並發讀但只能一個線程寫, 要這麼建立 HashTable執行個體:
//Thread safe HashTable
System.Collections.Hashtable htSyn = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
這樣, 如果有多個線程並發的企圖寫HashTable裡面的 item, 則同一時刻只能有一個線程寫, 其餘阻塞; 對讀的線程則不受影響。
另外一種方法就是使用lock語句,但要lock的不是HashTable,而是其SyncRoot;雖然不推薦這種方法,但效果一樣的,因為原始碼就是這樣實現的:
//Thread safeprivate static System.Collections.Hashtable htCache = new System.Collections.Hashtable ();public static void AccessCache (){ lock ( htCache.SyncRoot ) { htCache.Add ( "key", "value" ); //Be careful: don't use foreach to operation on the whole collection //Otherwise the collection won't be locked correctly even though indicated locked //--by MSDN }}//Is equivalent to 等同於 (lock is equivalent to Monitor.Enter and Exit()public static void AccessCache (){ System.Threading.Monitor.Enter ( htCache.SyncRoot ); try { /* critical section */ htCache.Add ( "key", "value" ); //Be careful: don't use foreach to operation on the whole collection //Otherwise the collection won't be locked correctly even though indicated locked //--by MSDN } finally { System.Threading.Monitor.Exit ( htCache.SyncRoot ); }}
7. Stack類
棧,後進先出。push方法入棧,pop方法出棧。
System.Collections.Stack stack=new System.Collections.Stack(); stack.Push(1); stack.Push(2); System.Console.WriteLine(stack.Peek()); while(stack.Count>0) { System.Console.WriteLine(stack.Pop()); } 8.Queue類 隊列,先進先出。enqueue方法入隊列,dequeue方法出隊列。 System.Collections.Queue queue=new System.Collections.Queue(); queue.Enqueue(1); queue.Enqueue(2); System.Console.WriteLine(queue.Peek()); while(queue.Count>0) { System.Console.WriteLine(queue.Dequeue()); }
本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/snlei/archive/2009/02/26/3939206.aspx