描述: 哈希表存放 key、values ,key值可以用于快速调取用,values 对应object类型,也就是说所有类型。
实例:
1.HashTable存放学生的成绩
1Hashtable ht1 = new Hashtable(); //创建一个Hashtable实例 2 ht1.Add("张三", "100"); //添加keyvalue键值对 3 ht1.Add("李四", "100"); 4 ht1.Add("王五", "100"); 5 ht1.Add("赵六", "200"); 6 string capital1 = (string)ht["王五"];//根据Key值获取信息 7 ht.Remove("赵六"); //移除一个keyvalue键值对 ht.Clear(); //移除所有元素 8 object value2 = ht["赵六"];//直接根据key取值,判断类型在进行转化 9 if (value2 is string) 10 { 11 12 } 13 foreach (DictionaryEntry de in ht) //ht为一个Hashtable实例,遍历哈希表 object对象 14 { 15 Control cc = (Control)de.Value; 16 } 17 //添加数据时Hashtable快。频繁调用数据时Dictionary快。
2.System.Collections下的哈希表(Hashtable)和System.Collections.Generic下的字典(Dictionary)都可用作lookup table,下面比较一下二者的执行效率。
1Stopwatch sw = new Stopwatch(); 2Hashtable hashtable = new Hashtable(); 3Dictionary<string, int> dictionary = new Dictionary<string, int>(); 4int countNum = 1000000; 5 6sw.Start(); 7for (int i = 0; i < countNum; i++) 8{ 9 hashtable.Add(i.ToString(), i); 10} 11sw.Stop(); 12Console.WriteLine(sw.ElapsedMilliseconds); //输出: 744 13 14sw.Restart(); 15for (int i = 0; i < countNum; i++) 16{ 17 dictionary.Add(i.ToString(), i); 18} 19sw.Stop(); 20Console.WriteLine(sw.ElapsedMilliseconds); //输出: 489 21 22sw.Restart(); 23for (int i = 0; i < countNum; i++) 24{ 25 hashtable.ContainsKey(i.ToString()); 26} 27sw.Stop(); 28Console.WriteLine(sw.ElapsedMilliseconds); //输出: 245 29 30sw.Restart(); 31for (int i = 0; i < countNum; i++) 32{ 33 dictionary.ContainsKey(i.ToString()); 34} 35sw.Stop(); 36Console.WriteLine(sw.ElapsedMilliseconds); //输出: 192
Dictionary<K,V>是泛型的,当K或V是值类型时,其速度远远超过Hashtable。