Thursday, September 17, 2009

Differences between HashMap and HashTable

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

For new code, use HashMap as much as possible.

If you want Keys in HashMap to be Case - Insensitive, follow this technique:
http://www.velocityreviews.com/forums/t140140-case-insensitive-keys-using-collections.html
* Store keys in LowerCase while popluating the map.
* Always use .LowerCase() on lookupKey before doing a get()

Complexity of Lookup on HashMap is not alway O(1). It depends on HashMap size. If multiple keys in HashMap match a lookupKey, then it traverses linear O(n) on matched Keys.

4 Ways to traverse HashMap - Link

2 comments:

diƤt pillen said...

Hashtable has synchronization overhead, but unless you are actually using multiple thread to access it this overhead is very low on most platforms. Contention is what make synchronization expensive.

HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again. This can improve the distribution of the keys and hence the performance of the Map. It does take more time to compute though. This is a useful feature as many hashCode implementations are not very good.

Lakshman Abburi said...

Thanks for the comment Pillen. Good details to add.