Thursday, 13 August 2015

Hashtable Vs HashMap in Java

HashMap and Hashtable are the hashing/mapping libraries of java that I have used. However, I never went into details such as what are their implementations, why there are two of them with the same purpose, or if they are different, when should I use them?
  1. HashMap allows null values to be stored in the key or values. Hashtable doesn't. So if you are not absolutely sure if your keys or values will be non-null go for HashMap to avoid Runtime Errors.
  2. HashMap is not synchronized whereas Hashtable are. So, If your application is multi-threaded and these insert or remove keys from the map then you should use Hashtable. Lest, one of the threads modifies the map and the other thread will get inconsistent data.
  3. Because of the extra thread safety and synchronization issues that Hashtable handles, they are slower than HashMap. I tested get and put methods of both of them for 1 million inserts and access over 10 attempts of random data. Average time for insertion in HashMap was 309ms while that of Hashtable was 1177ms. Whereas average time for retrieval in HashMap was 87ms while that of Hashtable was 143ms. 
  4. HashMap uses Iterator class for iterating whereas Hashtable uses Enumerator. This means that if the HashMap is structurally modified after creating the Iterator(i.e. some element is added or removed from the map), then a ConcurrentModificationException will be thrown. Hashtable is fail-safe from this.
To summarize, we can use HashMap whenever we are not bothered about multi-threading or other concurrent modifications on the map. It will allow nulls to be part of the map and also give faster performance. If multiple threads concurrently modify or if we are strict about nulls not being a part of the map then Hashtable should be used.  

No comments:

Post a Comment