在大多数编程语言中,字典比哈希表更受欢迎。这背后的原因是什么?


当前回答

Dictionary<>是泛型类型,因此它是类型安全的。

您可以在HashTable中插入任何值类型,这有时可能会引发异常。但是Dictionary<int>只接受整数值,类似地Dictionary><string>只接受字符串。

因此,最好使用Dictionary<>而不是HashTable。

其他回答

因为Dictionary是一个泛型类(Dictionary<TKey,TValue>),所以访问其内容是类型安全的(即,不需要像Hashtable那样从Object转换)。

比较

var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];

to

var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;

然而,Dictionary在内部实现为哈希表,因此技术上它的工作方式相同。

仅供参考:在.NET中,Hashtable是线程安全的,可供多个读线程和一个写线程使用,而在Dictionary中,公共静态成员是线程安全,但不能保证任何实例成员都是线程安全。

因此,我们不得不将所有词典改回Hashtable。

Dictionary<>是泛型类型,因此它是类型安全的。

您可以在HashTable中插入任何值类型,这有时可能会引发异常。但是Dictionary<int>只接受整数值,类似地Dictionary><string>只接受字符串。

因此,最好使用Dictionary<>而不是HashTable。

差异

Dictionary Hashtable
Generic Non-Generic
Needs own thread synchronization Offers thread safe version through Synchronized() method
Enumerated item: KeyValuePair Enumerated item: DictionaryEntry
Newer (> .NET 2.0) Older (since .NET 1.0)
is in System.Collections.Generic is in System.Collections
Request to non-existing key throws exception Request to non-existing key returns null
potentially a bit faster for value types bit slower (needs boxing/unboxing) for value types

相似之处:

两者都是内部哈希表==根据关键字快速访问许多项数据两者都需要不可变和唯一的密钥两者的键都需要自己的GetHashCode()方法

其他.NET集合:

(要使用的候选项,而不是字典和哈希表)

ConcurrentDictionary-线程安全(可以从多个线程同时安全访问)HybridDictionary-优化的性能(适用于少数项目,也适用于许多项目)OrderedDictionary-值可以通过int索引访问(按添加项的顺序)SortedDictionary-自动排序的项目StringDictionary-强类型并针对字符串进行了优化(现在不推荐使用Dictionary<string,string>)

在大多数编程语言中,字典优先于哈希表

我认为这不一定是真的,大多数语言都有这两种语言,这取决于他们喜欢的术语。

然而,在C#中,很明显的原因(对我来说)是C#HashTables和System.Collections命名空间的其他成员在很大程度上已经过时了。它们出现在c#V1.1中。它们已从C#2.0替换为System.Collections.Generic命名空间中的Generic类。