C#中的HashSet, HashTable, Dictionary的区别【转】

HashSet和Python中的Set差不多,都是为逻辑运算准备的,HashSet不允许数据有重复,且存入的时单值不是键值对。
HashTable和Dictionary差不多,但是他们的实现方式时不同的,Dictionary俗称字典,里面存放的时键值对,即KeyValuePair,且支持泛型,而HashTable国内一般译为哈希表,但是在我看来,为了更好表达它的本质,翻译为散列表比较好,因为HashTable里面村的key时以散列的方式存储的,但是Dictionary里面是按顺序的方式存的KeyValuePair。

实践了才能记得住,所以此处以LeetCode第500题为例来说明这一点。

    public string[] FindWords(string[] words) { for(int i=0;i<words.Length;i++) { words[i] = words[i].ToLower(); } string arr1 = "qwertyuiop"; string arr2 = "asdfghjkl"; string arr3 = "zxcvbnm"; HashSet<int> map1 = new HashSet<int>(); Dictionary<char, int> map2 = new Dictionary<char, int>(); Hashtable map3 =new Hashtable(); for(int i=0;i<arr1.Length;i++) { map1.Add(i); map2.Add(arr1[i], 1); map3.Add(arr1[i], 1); } for(int i=0; i<arr2.Length;i++) { map1.Add(i); map2.Add(arr2[i], 2); map3.Add(arr2[i], 2); } for(int i=0; i<arr3.Length;i++) { map1.Add(i); map2.Add(arr3[i], 2); map3.Add(arr3[i], 2); } int flag = 0; List<string> lstStr = new List<string>(); for(int i=0; i<words.Length;i++) { flag = 0; for(int j=0;j<words[i].Length;j++) { if(map2[words[i][0]] != map2[words[i][j]]) { flag = 1; break; } } if(flag == 0) lstStr.Add(words[i]); } return lstStr.ToArray(); }

其中map1是HashSet,map2是Dictionary, map3是HashTable,但是若将if判断中的map2改成map3会怎么样呢?看看这一段代码

object a = 1; object b = 1; Console.WriteLine(a.GetType()); if(a==b) { Console.WriteLine("a==b"); }

结果是a不等于b,为什么呢,因为他们内容相同但是地址不同,但是将==改为equals的比较就可以了,具体请查阅equals和==的区别(注意这里略绕哦)。

这里面的问题在于HashTable总是把所有变量当成Object所以才会出这个问题,而Dictionary类型则是指定key和value的类型。

另外Dictionary数据结构再单线程使用会比较快,存放值类型的数据也会比HashTable快,这是因为HashTable对于存入的数无论是值类型还是引用类型都会变成object类型关于这一点,再看一个小例子。

https://blog.csdn.net/github_34777264/article/details/79625374

猜你喜欢

转载自www.cnblogs.com/mazhenyu/p/9186648.html