Difference between Dictionary and Hashtable

Possible Duplicate:
Why Dictionary is preferred over hashtable in C#?

What is the difference between Dictionary and Hashtable. How to decide which one to use?


Simply, Dictionary<TKey,TValue> is a generic type, allowing:

  • static typing (and compile-time verification)
  • use without boxing
  • If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

    A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue> .


    Lets give an example that would explain the difference between hashtable and dictionary.

    Here is a method that implements hashtable

    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;
        //}
    }
    

    The following is for dictionary

      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;
        }
      }
    

    There is one more important difference between a HashTable and Dictionary. If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary

    链接地址: http://www.djcxy.com/p/16360.html

    上一篇: HashMap Java 8实现

    下一篇: 字典和哈希表之间的区别