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


当前回答

差异

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>)

其他回答

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

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

注意,文档中说:“Dictionary<(Of<(TKey,TValue>)>)类是作为哈希表实现的”,而不是“Dictionary<(Of<(TKey,TValue>)>类是作为HashTable实现的”

字典没有实现为哈希表,但它是按照哈希表的概念实现的。由于使用了泛型,该实现与HashTable类无关,尽管微软内部可能使用了相同的代码,并用TKey和TValue替换了Object类型的符号。

在.NET 1.0中,泛型不存在;这是HashTable和ArrayList最初开始的地方。

集合和泛型对于处理一组对象非常有用。在.NET中,所有集合对象都位于接口IEnumerable下,该接口又具有ArrayList(索引值)和HashTable(键值)。在.NET framework 2.0之后,ArrayList和HashTable被List和Dictionary取代。现在,Arraylist和HashTable在现在的项目中不再使用。

谈到HashTable和Dictionary之间的区别,Dictionary是泛型的,而Hastable不是泛型的。我们可以向HashTable中添加任何类型的对象,但在检索时需要将其转换为所需的类型。因此,它不是类型安全的。但对于字典,在声明自身时,我们可以指定键和值的类型,因此在检索时不需要强制转换。

我们来看一个示例:

散列表

class HashTableProgram
{
    static void Main(string[] args)
    {
        Hashtable ht = new Hashtable();
        ht.Add(1, "One");
        ht.Add(2, "Two");
        ht.Add(3, "Three");
        foreach (DictionaryEntry de in ht)
        {
            int Key = (int)de.Key; //Casting
            string value = de.Value.ToString(); //Casting
            Console.WriteLine(Key + " " + value);
        }

    }
}

词典

class DictionaryProgram
{
    static void Main(string[] args)
    {
        Dictionary<int, string> dt = new Dictionary<int, string>();
        dt.Add(1, "One");
        dt.Add(2, "Two");
        dt.Add(3, "Three");
        foreach (KeyValuePair<int, String> kv in dt)
        {
            Console.WriteLine(kv.Key + " " + kv.Value);
        }
    }
}

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

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

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

根据我使用.NET Reflector所看到的:

[Serializable, ComVisible(true)]
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
    // Fields
    private Hashtable hashtable;

    // Methods
    protected DictionaryBase();
    public void Clear();
.
.
.
}
Take note of these lines
// Fields
private Hashtable hashtable;

因此,我们可以确定DictionaryBase在内部使用HashTable。