Difference between HashMap and HashTable in Java
HasMap | HashTable |
HashMap method is not Synchronized | HashTable every method is synchronized |
multiple thread can operates simultenously hence hashmap object is not thread safe | At a time only one thread is allowed to operate an hashtable object hence it is threadsafe |
thread are not required to wait hence relatively performance is high | It increase waiting time of thread hence performance is slow |
HashMap allows one null key and any number of null values | Hashtable does not allow null keys or values otherwise we will get null pointer exception |
introduce in 1.2 version & it is non-legacy | introduce in 1.0 and it is legacy |
We can make the HashMap as synchronized throughMap m = Collections.synchronizedMap(hashMap); | Hashtable is internally synchronized and can’t be unsynchronized. |
HashMap is traversed by Iterator. | Hashtable is traversed by Enumerator and Iterator. |
In HashMap implementation LinkedHashMap maintains the insertion order and TreeMap sorts the mappings based on the ascending order of keys | Hashtable doesn’t guarantee any kind of order. It doesn’t maintain the mappings in any particular order |
Iterator of the HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except iterator’s own remove() method | Enumerator for the Hashtable is not fail-fast. |