Why is Dictionary preferred over Hashtable?
In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
For what it's worth, a Dictionary is (conceptually) a hash table.
If you meant "why do we use the Dictionary<TKey, TValue>
class instead of the Hashtable
class?", then it's an easy answer: Dictionary<TKey, TValue>
is a generic type, Hashtable
is not. That means you get type safety with Dictionary<TKey, TValue>
, because you can't insert any random object into it, and you don't have to cast the values you take out.
Interestingly, the Dictionary<TKey, TValue>
implementation in the .NET Framework is based on the Hashtable
, as you can tell from this comment in its source code:
The generic Dictionary was copied from Hashtable's source
Source
Dictionary
<<<>>> Hashtable
differences:
Synchronized()
method KeyValuePair
<<<>>> Enumerated item: DictionaryEntry
Dictionary
/ Hashtable
similarities:
GetHashCode()
method Similar .NET collections (candidates to use instead of Dictionary and Hashtable):
ConcurrentDictionary
- thread safe (can be safely accessed from several threads concurrently) HybridDictionary
- optimized performance (for few items and also for many items) OrderedDictionary
- values can be accessed via int index (by order in which items were added) SortedDictionary
- items automatically sorted StringDictionary
- strongly typed and optimized for strings Because Dictionary
is a generic class ( Dictionary<TKey, TValue>
), so that accessing its content is type-safe (ie you do not need to cast from Object
, as you do with a Hashtable
).
Compare
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
However, Dictionary
is implemented as Hashtable
inside, so technically it works the same way.
上一篇: 在C#中解析命令行参数的最佳方法?