简体   繁体   中英

What is the primary difference between Dictionary and Hashtable

What is the difference between Dictionary and Hashtable. How can i come to conclusion on which to use?Can anyone please help me?

The Dictionary class differs from the Hashtable class in more ways than one. In addition to being strongly-typed, the Dictionary also employs a different collision resolution strategy than the Hashtable class, using a technique referred to as chaining.

You can read this article: http://msdn.microsoft.com/en-us/library/ms379571(v=vs.80).aspx#datastructures20_2_topic6

It's really useful.

Hashtable is obsolete. Always use Dictionary.

I am newbie in hashtables too, but...

Dictionary is a basic table with two columns (Key and Value, both has certain types) and lots of rows you add later. You will see that in dictionary you give a key and dictionary gives you value you added previously by the absolutely same key.

In hashtable things are slightly different. You have table with two columns again (Key and Value, both are of "object" type). The keys might be not unique. Now you virtualy have two tables: one with two columns: Key and Hash, and other one with again two columns Hash and Value. Hash is some integer value got from Key. It turns out that while Keys might be unique, Hashes may be not. [Yet I'm not sure about this... so I said "virtualy"...]

Now example:

Hashtable ht = new Hashtable();
// Key of type Int32
ht[16] = "That is Int32";
// Key of type String
ht["Blah"] = 15;
// Key of type Boolean
ht[false] = "That is boolean";
// Key of type String
ht["Hohoho"] = false;

And later you can access any value stored in Hashtable just using keys (if there are no such key it returns null):

Console.WriteLine("ht[{0}] = {1};", 16, ht[16] ?? "null");
Console.WriteLine("ht[{0}] = {1};", "Test", ht["Test"] ?? "null"); // doesnt exist eh...
Console.WriteLine("ht[{0}] = {1};", false, ht[false] ?? "null");
Console.WriteLine("ht[{0}] = {1};", "Hohoho", ht["Hohoho"] ?? "null");

To sumarize:

Dictionary is this:

[ Key ][ Value ]
   A      1.5
   B      1.6
   C      -8
     ....

And Hashtable probabily is this:

[ Key ][ Hash ]
   A      1
   B      2
   C     -99
      ...

[ Hash ][ Value ]
   -99      -8
    1       1.6
    2       1.5
      ....

I hope this is anything helpful. Anyone who could explain it better, do not hesitate to do so.

Thank you and good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM