Tuesday, April 28, 2015

HashMap vs HashTable

Differences:
  1. HashMap allows null values as key and value whereas HashTable doesn't.
    maps.put(null, 7);
    maps.put(null, 15);
    The key is null and the value of 15 overwrite 7.
  2. HashMap is non synchronized whereas Hashtable is synchronized.
  3. HashTable is the only class other than vector which have method return enumerator to iterate The values.
  4. The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.
Similarities:
Both HashMap and HashTable does not guarantee that the order of the map will remain constant over time. 

When to use HashMap and Hashtable?

1. Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications.
In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi Threaded Application
We should avoid using HashTable, as the class is now obsolete in latest Jdk 1.8.
Oracle has provided a better replacement of HashTable named ConcurrentHashMap.
For multithreaded application prefer ConcurrentHashMap instead of Hashtable. It would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

HashMapHashTable
SynchronizedNoYes
Thread-SafeNoYes
Null Keys and Null valuesOne null key ,Any null valuesNot permit null keys and values
Iterator typeFail fast iteratorFail safe iterator
PerformanceFastSlow in comparision
Superclass and LegacyAbstractMap , NoDictionary , Yes

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...