Tuesday, 9 July 2013

Difference between Hahtable and Dictionary


-> Dictionary and Hash table are collection of data structure to hold data as key/value pairs.

-> Hashatable is a collection of key and value pair.
Hastable is not Generic.It is a loosely-typed data structure, so you can add keys and values of any type to the Hashtable. but while reteriving we need to Cast it to the required Type. So, it is not type safe.

where as

Dictionary is generic.The Dictionary class is a type-safe Hashtable implementation, and the keys and values are strongly types.When creating a Dictionary instance, you must specify the data types for both the key and value.so no need to cast while retreiving.

->When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of 'KeyNotFoundException' while hashtable returns null value.

->When we retrieve the record in collection the hashtable does not maintain the order of entries
while dictionary maintains the order of entries by which entries were added.

->Dictionary is faster than a Hashtable because there is no boxing and unboxing.

->  While using large collection of key-value pair hashtable would be considered more effecient than Dictionary.

Use a hashtable (dictionary) when you want fast look up access to an item based on a key


Example of 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);
        }

    }
}

Example of Dictionary

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> pair in dt)
        {
            Console.WriteLine(pair.Key + " " + pair.Value);
        }
    }
}

No comments:

Post a Comment