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 but
HashMapis not thread-safe and cannot be shared between multiple threads without proper synchronization. To use
HashMapin multi-threading you need to synchronize the
Collections.synchronizeMap(hashMap)or if you are using Java 5+ then you can consider
- 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 whereas
HashMapallows 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 the
HashMapcannot be retrieved.
HashTablealso don’t retains the order in which it was added.
- HashTable Enumerator vs HashMap Iterator: Important difference between
HashMapis that Enumerator in HashTable is not fail-fast whereas Iterator in
HashMapis a fail-fast iterator.
- Performance of HashTable Vs HashMap: As
HashMapis sychronized and thread-safe, performance of
HashTableis compromised whereas
HashMapgives better performance than
HashTablebecause of lack of sychronization. In single-threaded environment it is recommended to use
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.