Both HashTable
and HashMap
are java collections and implements java.util.Map interface. Difference between HashTable and HashMap is the most common interview question. Many of the candidates who face the interview struggle to answer this question.
Difference between HashTable and HashMap in Java
- Thread Safe:
HashTable
is thread-safe and can be shared between multiple threads butHashMap
is not thread-safe and cannot be shared between multiple threads without proper synchronization. To useHashMap
in multi-threading you need to synchronize theHashMap
asCollections.synchronizeMap(hashMap)
or if you are using Java 5+ then you can considerConcurrentHashMap
. - Null Keys and Values: Another comparison point here is whether these java collection allows you to null Keys and Values.
HashTable
don’t allow you to use null Keys and Values whereasHashMap
allows you to null keys and values. - Order of the Elements:
HashMap
does not guarantee you the order of the map i.e the order in which you have added the elements in theHashMap
cannot be retrieved.HashTable
also don’t retains the order in which it was added. - HashTable Enumerator vs HashMap Iterator: Important difference between
HashTable
andHashMap
is that Enumerator in HashTable is not fail-fast whereas Iterator inHashMap
is a fail-fast iterator. - Performance of HashTable Vs HashMap: As
HashMap
is sychronized and thread-safe, performance ofHashTable
is compromised whereasHashMap
gives better performance thanHashTable
because of lack of sychronization. In single-threaded environment it is recommended to useHashMap
overHashTable
.
NOTE: Fail-fast feature is of Iterators. If the map is structurally modified at any time after the iterator is created, except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in case of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Fail-fast behavior of iterator is not a guaranteed behavior and will be done by JVM on best effort.