代码之家  ›  专栏  ›  技术社区  ›  blitzkriegz

字典和哈希表之间的差异[重复]

  •  102
  • blitzkriegz  · 技术社区  · 17 年前

    可能重复:
    Why Dictionary is preferred over hashtable in C#?

    字典和哈希表的区别是什么。如何决定使用哪一个?

    7 回复  |  直到 9 年前
        1
  •  196
  •   Gabe Timothy Khouri    15 年前

    仅仅 Dictionary<TKey,TValue> 是泛型类型,允许:

    • 静态类型(和编译时验证)
    • 不用拳击

    如果您是.NET2.0或更高版本,您应该 更喜欢 字典<TKey,TValue> (和其他通用集合)

    一个微妙但重要的区别是 Hashtable 使用单个写入线程支持多个读卡器线程,而 Dictionary 不提供线程安全性。如果您需要通用字典的线程安全性,则必须实现自己的同步或(在.NET 4.0中)使用 ConcurrentDictionary<TKey, TValue> .

        2
  •  85
  •   Pritom Nandy    15 年前

    让我们举一个例子来解释哈希表和字典之间的区别。

    public void MethodHashTable()
    {
        Hashtable objHashTable = new Hashtable();
        objHashTable.Add(1, 100);    // int
        objHashTable.Add(2.99, 200); // float
        objHashTable.Add('A', 300);  // char
        objHashTable.Add("4", 400);  // string
    
        lblDisplay1.Text = objHashTable[1].ToString();
        lblDisplay2.Text = objHashTable[2.99].ToString();
        lblDisplay3.Text = objHashTable['A'].ToString();
        lblDisplay4.Text = objHashTable["4"].ToString();
    
    
        // ----------- Not Possible for HashTable ----------
        //foreach (KeyValuePair<string, int> pair in objHashTable)
        //{
        //    lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
        //}
    }
    

    以下是字典

      public void MethodDictionary()
      {
        Dictionary<string, int> dictionary = new Dictionary<string, int>();
        dictionary.Add("cat", 2);
        dictionary.Add("dog", 1);
        dictionary.Add("llama", 0);
        dictionary.Add("iguana", -1);
    
        //dictionary.Add(1, -2); // Compilation Error
    
        foreach (KeyValuePair<string, int> pair in dictionary)
        {
            lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
        }
      }
    
        3
  •  24
  •   Rohit Gupta    16 年前

    哈希表和字典还有一个更重要的区别。如果使用索引器从哈希表中获取值,哈希表将成功为不存在的项返回null,而如果尝试使用字典中不存在的索引器访问项,字典将抛出错误

        4
  •  13
  •   Community Mohan Dere    9 年前

    字典是类型化的(因此valuetypes不需要装箱),哈希表不是类型化的(因此valuetypes需要装箱)。哈希表比dictionary IMHO有更好的获取值的方法,因为它总是知道值是一个对象。虽然如果您使用的是.NET3.5,为dictionary编写一个扩展方法以获得类似的行为是很容易的。

    如果每个键需要多个值,请在此处查看我的MultiValueDictionary源代码: multimap in .NET

        5
  •  10
  •   Pranav Singh    15 年前

    要添加一个差异:

    尝试访问不存在的键会在字典中出现运行时错误,但在哈希表中不会出现问题,因为它返回null而不是error。

    例如

           //No strict type declaration
            Hashtable hash = new Hashtable();
            hash.Add(1, "One");
            hash.Add(2, "Two");
            hash.Add(3, "Three");
            hash.Add(4, "Four");
            hash.Add(5, "Five"); 
            hash.Add(6, "Six");
            hash.Add(7, "Seven");
            hash.Add(8, "Eight");
            hash.Add(9, "Nine");
            hash.Add("Ten", 10);// No error as no strict type
    
            for(int i=0;i<=hash.Count;i++)//=>No error for index 0
            {
                //Can be accessed through indexers
                Console.WriteLine(hash[i]);
            }
            Console.WriteLine(hash["Ten"]);//=> No error in Has Table
    

    此处键0&没有错误;也适用于键“十”(注:t较小)

    //Strict type declaration
            Dictionary<int,string> dictionary= new Dictionary<int, string>();
            dictionary.Add(1, "One");
            dictionary.Add(2, "Two");
            dictionary.Add(3, "Three");
            dictionary.Add(4, "Four");
            dictionary.Add(5, "Five");
            dictionary.Add(6, "Six");
            dictionary.Add(7, "Seven");
            dictionary.Add(8, "Eight");
            dictionary.Add(9, "Nine");
            //dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added
    
            //for i=0, key doesn't  exist error
            for (int i = 1; i <= dictionary.Count; i++)
            {
                //Can be accessed through indexers
                Console.WriteLine(dictionary[i]);
            }
            //Error : The given key was not present in the dictionary.
            //Console.WriteLine(dictionary[10]);
    

    此处显示键0的错误&也适用于键10,因为这两项在字典中都不存在,所以在尝试访问时出现运行时错误。

        6
  •  6
  •   Rashmi Pandit    8 年前

    Hashtable类是一种特定类型的字典类,它使用一个整数值(称为哈希)来帮助存储其键。Hashtable类使用hash来加速对集合中特定键的搜索。NET中的每个对象都派生自对象类。此类支持GetHash方法,该方法返回唯一标识对象的整数。Hashtable类通常是一个非常有效的集合。Hashtable类的唯一问题是它需要一点开销,对于小集合(少于十个元素),开销会影响性能。

    两者之间有一些特殊的区别,必须加以考虑:

    哈希表:是非泛型集合,它的最大开销 集合是指它自动为您的值和 为了获得原始值,需要执行解装箱, 这些将降低应用程序性能,作为惩罚。

    字典:这是集合的泛型类型,其中没有隐式 装箱,所以无需拆箱,您将始终获得您的原始文件 存储的值,以便改进应用程序 表演

    第二个显著区别是:

    如果您试图从哈希表中访问 对于不存在的键,它将返回null 字典它会给你KeyNotFoundException。

        7
  •  3
  •   shiv govind    16 年前

    ILookup接口在.NET3.5中与linq一起使用。

    哈希表是弱类型的基类;字典库 抽象类是stronly类型的,并在内部使用哈希表。

    我发现字典有一个奇怪的地方,当我们在字典中添加多个条目时,条目添加的顺序保持不变。因此,如果我在字典上应用foreach,我将按照插入记录的相同顺序获取记录。

    然而,对于普通哈希表,情况并非如此,因为当我在哈希表中添加相同的记录时,顺序不会得到维护。就我所知,字典是基于哈希表的,如果这是真的,为什么我的字典保持顺序而哈希表不保持顺序?

    至于它们的行为为何不同,这是因为泛型字典实现了一个哈希表,而不是基于System.Collections.hashtable。通用字典实现基于从列表中分配键值对。然后使用哈希表存储桶对这些数据进行索引,以进行随机访问,但当它返回枚举数时,它只是按顺序遍历列表,只要不重复使用条目,这就是插入顺序。

    希夫戈文