In C#, I find myself using a List<T>
, IList<T>
or IEnumerable<T>
99% of the time. Is there a case when it would be better to use a HashTable
(or Dictionary<T,T>
in 2.0 and above) over these?
Edit:
As pointed out, what someone would like to do with the collection often dictates what one should be using, so when would you use a Hashtable
/Dictonary<T,T>
over a List<T>
?
When to use HashMap and Hashtable? HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications . We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 .
The main advantage of hash tables over other data structures is speed . The access time of an element is on average O(1), therefore lookup could be performed very fast. Hash tables are particularly efficient when the maximum number of entries can be predicted in advance.
Cryptographic hash functions are very commonly used in password verification. Let's understand this using an Example: When you use any online website which requires a user login, you enter your E-mail and password to authenticate that the account you are trying to use belongs to you.
Hash tables tend to be faster when it comes to searching for items. In arrays, you have to loop over all items before you find what you are looking for while in a hash table you go directly to the location of the item. Inserting an item is also faster in Hash tables since you just hash the key and insert it.
Maybe not directly related to the OPs question, but there's a useful blog post about which collection structure to use at: SortedSets
Basically, what you want to do with the collection determines what type of collection you should create.
To summarise in more detail:
Use SortedSet if you want to access a collection in a predefined order (most common usage being to access the collection in order)
Overall, use Dictionary if you want to access / modify items by key in no particular order (preferred over list as that's generally done in order, preferred over enumeration as you can't modify an enumeration, preferred over hashtable as that's not strictly typed, preferred over sortedlist when you don't need keys sorted)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With