Monday, September 14, 2009

Hashtable and HashMap

In the java's collections framework we have two classes HashMap and Hashtable which implement the map interface.Both of them perform the same function of storing data in key - value pair, but Hashtable was older version of HashMap. Hashtable is synchronized means all the methods in the Hashtable class are synchronized i.e they are thread safe. Also if there is a difference in the naming convention, notice that the 't' is in lower case but the 'M' in HashMap is upper case following the camel case convention. HashMap is faster for iteration as compared to Hashtable as it is not synchronised. It is recommended to use HashMap unless you have a very good reason to use Hashtable.

Another point of difference is that HashMap can have multiple null values but the keys of those values should be different. Also there can exist one null key in the HashMap but there cannot be any null keys or even values for that matter in a Hashtable.