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:
HashTableis thread-safe and can be shared between multiple threads butHashMapis not thread-safe and cannot be shared between multiple threads without proper synchronization. To useHashMapin multi-threading you need to synchronize theHashMapasCollections.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.
HashTabledon’t allow you to use null Keys and Values whereasHashMapallows you to null keys and values. - Order of the Elements:
HashMapdoes not guarantee you the order of the map i.e the order in which you have added the elements in theHashMapcannot be retrieved.HashTablealso don’t retains the order in which it was added. - HashTable Enumerator vs HashMap Iterator: Important difference between
HashTableandHashMapis that Enumerator in HashTable is not fail-fast whereas Iterator inHashMapis a fail-fast iterator. - Performance of HashTable Vs HashMap: As
HashMapis sychronized and thread-safe, performance ofHashTableis compromised whereasHashMapgives better performance thanHashTablebecause of lack of sychronization. In single-threaded environment it is recommended to useHashMapoverHashTable.
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.