C#中哈希表(HashTable)的用法詳解


描述: 哈希表存放 key、values ,key值可以用於快速調取用,values 對應object類型,也就是說所有類型。

實例:

1.HashTable存放學生的成績

   Hashtable ht1 = new Hashtable(); //創建一個Hashtable實例
            ht1.Add("張三", "100"); //添加keyvalue鍵值對
            ht1.Add("李四", "100");
            ht1.Add("王五", "100");
            ht1.Add("趙六", "200");
            string capital1 = (string)ht["王五"];//根據Key值獲取信息
            ht.Remove("趙六"); //移除一個keyvalue鍵值對 ht.Clear(); //移除所有元素
            object value2 = ht["趙六"];//直接根據key取值,判斷類型在進行轉化
            if (value2 is string)
            {

            }
            foreach (DictionaryEntry de in ht) //ht為一個Hashtable實例,遍歷哈希表 object對象
            {
                Control cc = (Control)de.Value;  
            }
            //添加數據時Hashtable快。頻繁調用數據時Dictionary快。

2.System.Collections下的哈希表(Hashtable)和System.Collections.Generic下的字典(Dictionary)都可用作lookup table,下面比較一下二者的執行效率。

Stopwatch sw = new Stopwatch();
Hashtable hashtable = new Hashtable();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
int countNum = 1000000;

sw.Start();
for (int i = 0; i < countNum; i++)
{
    hashtable.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);  //輸出: 744

sw.Restart();
for (int i = 0; i < countNum; i++)
{
    dictionary.Add(i.ToString(), i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);  //輸出: 489

sw.Restart();
for (int i = 0; i < countNum; i++)
{
    hashtable.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);  //輸出: 245

sw.Restart();
for (int i = 0; i < countNum; i++)
{
    dictionary.ContainsKey(i.ToString());
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);  //輸出: 192

Dictionary<K,V>是泛型的,當K或V是值類型時,其速度遠遠超過Hashtable。

 
         
         
        
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM