What is the difference between a Hash Table and a Dictionary?
1. Hashtable is threadsafe and while Dictionary is not.
2. Dictionary is type safe which means that the values need not be boxed while Hashtable
values need to be boxed or unboxed because it stores the values and keys as
objects.
3. 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.
4. When using large collection of key value pairs hashtable would be considered more
efficient than dictionary.
5. 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.
6. Dictionary relies on chaining whereas Hashtable relies on rehashing.
Write a program to build a simple phone book, with name and phone number – which one would you use for this?
A dictionarypublic class PhoneBook
{
Dictionary
public void Entries()
{
Book.Add(12345, "Rishi");
Book.Add(23456, "Sarthak");
Book.Add(34567, "Bholu");
foreach (var s in Book)
{
Console.WriteLine("Name :{1}, Phone : {0}", s.Key, s.Value);
}
}
}
No comments:
Post a Comment