Difference between HashMap and HashTable in Java

  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
  2. HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the Hashtable is fail-safe because enumerator for the Hashtable is not throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator‘s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms

  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
Parameter Hashmap Hashtable
Synchronized Not Syncronized Syncronized
Null key and Value Allows one null key and any number of null values Not allow null keys or values
Fail fast Iterator in Hashmap is fail fast Enumeration in Hashtable is not fail fast
ThreadSafe No Yes
Extends Extends AbstractMap class Extends Dictionary class
Performance Faster then Hashtable Slower then Hashmap

Note – You can synchonized a HashMap with the help of Collections.synchonizedMap(hashmap)

Map map=Collections.synchonizedMap(hashmap)

Syncronized →Being synchronized means that operation is thread safe, so only one thread can access the table at a time.

Fail safe – Fail-fast means when you try to modify the content when you are iterating, it will throw ConcurrentModification Exception and fail immediately.

For HashMap Itration:

Set keys = hashMap.keySet();
for (Object key : key) {
    hashMap.put(someObject, someValue); //it will throw the ConcurrentModificationException
}

For HashTable Enumeration:

Enumeration keys = hashTable.keys();
 for (Enumeration e = v.elements() ; e.hasMoreElements() ; e.nextElement()) {
      hashTable.put(someKey, someValue); //it works
 }

<<Previous <<   || Index ||   >>Next >>

Previous
Next