哈希表简述
在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中keyvalue键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对。
什么情况下使用哈希表
- 某些数据被高频率查询
- 数据量大
- 查询字段包含字符串类型
- 数据类型不统一
使用方法
用到的namespace
1 2
| using System.Collections; using System.Collections.Generic;
|
哈希表基本操作:
1 2 3 4 5 6 7 8 9 10 11
| //添加一个keyvalue键值对: HashtableObject.Add(key,value);
//移除某个keyvalue键值对: HashtableObject.Remove(key);
//移除所有元素: HashtableObject.Clear();
// 判断是否包含特定键key: HashtableObject.Contains(key);
|
哈希表使用多种数据类型的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| using System; using System.Collections;
class Program { static Hashtable GetHashtable() { Hashtable hashtable = new Hashtable(); hashtable.Add("名字", "小丽"); hashtable.Add("年龄", 22); return hashtable; }
static void Main() { Hashtable hashtable = GetHashtable();
string name = (string)hashtable["名字"]; Console.WriteLine(name);
int age = (int)hashtable["年龄"]; Console.WriteLine(age); } }
|
遍历哈希表
遍历哈希表需要用到DictionaryEntry
:
1 2 3 4 5
| for(DictionaryEntry de in ht) //ht为一个Hashtable实例 { Console.WriteLine(de.Key); //de.Key对应于keyvalue键值对key Console.WriteLine(de.Value); //de.Key对应于keyvalue键值对value }
|
遍历键:
1 2 3 4
| foreach (int key in hashtable.Keys) { Console.WriteLine(key); }
|
遍历值:
1 2 3 4
| foreach (string value in hashtable.Values) { Console.WriteLine(value); }
|
哈希表的效率
System.Collections下的哈希表(Hashtable)和System.Collections.Generic下的字典(Dictionary)都可用作lookup table,下面比较一下二者的执行效率。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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
|
由此可见,添加数据时Hashtable快。频繁调用数据时Dictionary快。
结论:Dictionary<K,V>是泛型的,当K或V是值类型时,其速度远远超过Hashtable。