1. 程式人生 > >c#雜湊表和字典的區別

c#雜湊表和字典的區別

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)

在.NET Framework中,Hashtable是System.Collections名稱空間提供的一個容器,用於處理和表現類似key/value的鍵值對,其中key通常可用來快速查詢,同時key是區分大小寫;value用於儲存對應於key的值。Hashtable中key/value鍵值對均為object型別,所以Hashtable可以支援任何型別的key/value鍵值對.

1.1 雜湊表的簡單操作

在雜湊表中新增一個key/value鍵值對:HashtableObject.Add(key,value); 
在雜湊表中去除某個key/value鍵值對:HashtableObject.Remove(key); 
從雜湊表中移除所有元素: HashtableObject.Clear(); 
判斷雜湊表是否包含特定鍵key: HashtableObject.Contains(key); 

雜湊表,名-值對。類似於字典(比陣列更強大)。雜湊表是經過優化的,訪問下標的物件先雜湊過。如果以任意型別鍵值訪問其中元素會快於其他集合。

GetHashCode()方法返回一個int型資料,使用這個鍵的值生成該int型資料。雜湊表獲取這個值最後返回一個索引,表示帶有給定雜湊的資料項在字典中儲存的位置。

 //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]; 

1.2  雜湊表遍歷

遍歷Hashtable物件的兩種方法:

由於Hashtable每個元素都是一個鍵/值對,因此元素型別既不是鍵的型別,也不是值的型別,而是DictionaryEntry型別。  

//方法一:遍歷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();

1.3 排序

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]);
}

1.4、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;雖然不推薦這種方法,但效果一樣的,因為原始碼就是這樣實現的:


private static System.Collections.Hashtable htCache = new System.Collections.Hashtable ();

public static void AccessCache ()



{

lock ( htCache.SyncRoot )

{

htCache.Add ( "key", "value" );

}

}



//Is equivalent to 等同於 (lock is equivalent to Monitor.Enter and Exit()

public static void AccessCache ()

{

System.Threading.Monitor.Enter ( htCache.SyncRoot );

try

{

htCache.Add ( "key", "value" );

}

finally

{

System.Threading.Monitor.Exit ( htCache.SyncRoot );

}

}

二 字典

Dictionary<Tkey,Tvalue>是Hastbale的泛型實現。 

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.");
}

2.1 字典遍歷

//遍歷鍵
foreach (string key in myDictionary.Keys)
{
    //遍歷某鍵的值
    foreach (string val in myDictionary[key])
    {

    }
}

由於 Dictionary 是鍵和值的集合,因此元素型別並非鍵型別或值型別。相反,元素型別是鍵型別和值型別的 KeyValuePair。 

foreach (KeyValuePair<string, string> kvp in myDictionary)
{
    string key = kvp.Key;//key包含了字典裡的鍵
    for (int i = 0; i < kvp.Value.Count; i++)
    {
        Response.Write(kvp.Value[i]);
    }
}