HashTable中的key/value均為object類型,由包含集合元素的存儲桶組成。存儲桶是 HashTable中各元素的虛擬子組,與大多數集合中進行的搜索和檢索相比,存儲桶可令搜索和檢索更為便捷。每一存儲桶都與一個哈希代碼關聯,該哈希代碼是使用哈希函數生成的並基於該元素的鍵。HashTable的優點就在於其索引的方式,速度非常快。如果以任意類型鍵值訪問其中元素會快於其他集合,特別是當數據量特別大的時候,效率差別尤其大。
HashTable的應用場合有:做對象緩存,樹遞歸算法的替代,和各種需提升效率的場合。
System.Collections.Hashtable ht = System.Collections.Hashtable();
ht.Add(, );
ht.Add(, );
ht.Add(, );
(ht.ContainsKey())
ht[] = ;
oValue = ht[];
(DictionaryEntry de ht)
{
Console.WriteLine(de.Key);
Console.WriteLine(de.Value);
}
System.Collections.IDictionaryEnumerator d = ht.GetEnumerator();
(d.MoveNext())
{
Console.WriteLine(, d.Entry.Key, d.Entry.Value);
}
ht.Clear();
Dictionary和HashTable內部實現差不多,但前者無需裝箱拆箱操作,效率略高一點。
System.Collections.Generic.Dictionary<, > fruits =
System.Collections.Generic.Dictionary<, >();
fruits.Add(, );
fruits.Add(, );
fruits.Add(, );
( i fruits.Keys)
{
Console.WriteLine(, i, fruits);
}
(fruits.ContainsKey())
{
Console.WriteLine();
}
ArrayList是一維變長數組,內部值為object類型,效率一般:
System.Collections.ArrayList list = System.Collections.ArrayList();
list.Add();
list.Add();
( i = ; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
HashTable是經過優化的,訪問下標的對象先散列過,所以內部是無序散列的,保證了高效率,也就是說,其輸出不是按照開始加入的順序,而Dictionary遍歷輸出的順序,就是加入的順序,這點與Hashtable不同。如果一定要排序HashTable輸出,只能自己實現:
System.Collections.ArrayList akeys = System.Collections.ArrayList(ht.Keys);
akeys.Sort();
( skey akeys)
{
Console.Write(skey + );
Console.WriteLine(ht[skey]);
}
HashTable與線程安全:
為了保證在多線程的情況下的線程同步訪問安全,微軟提供了自動線程同步的HashTable:
如果 HashTable要允許並發讀但只能一個線程寫, 要這麼創建 HashTable實例:
System.Collections.Hashtable htSyn = System.Collections.Hashtable.Synchronized( System.Collections.Hashtable());
這樣, 如果有多個線程並發的企圖寫HashTable裡面的 item, 則同一時刻只能有一個線程寫, 其余阻塞; 對讀的線程則不受影響。
另外一種方法就是使用lock語句,但要lock的不是HashTable,而是其SyncRoot;雖然不推薦這種方法,但效果一樣的,因為源代碼就是這樣實現的:
System.Collections.Hashtable htCache = System.Collections.Hashtable ();
AccessCache ()
{
( htCache.SyncRoot )
{
htCache.Add ( , );
}
}
AccessCache ()
{
System.Threading.Monitor.Enter ( htCache.SyncRoot );
{
htCache.Add ( , );
}
{
System.Threading.Monitor.Exit ( htCache.SyncRoot );
}
}