Hashtable VS HashMap
Hashing objects like HashMap and Hashtable are mostly used for storing and caching data as a key/value pairs inside the memory.
In this tutorial, we list the major similarities and differences between these 2 data types.
- Both expose the same interface for adding, removing and accessing elements from the memory.
- get(): retrieve an item by a key.
- remove(): remove an item by a key.
- put(): add an item
so both types can interchangeably be used for caching or storing key/value pairs inside the memory.
- Both belong to the same package java.util.
There are a lot of differences between HashMap and Hashtable, here below we list the major ones:
- Hashtable is implicitly synchronized, it works perfectly with multi-threaded environments. Upon each access, the thread acquires a lock on the Hashtable hence preventing any other thread from modifying it simultaneously. In contrast, HashMap is not thread safe and is only suitable for single-threaded environments. If you want to use HashMap in a multi threaded environment you can use ConcurrentHashMap.
- HashMap is faster than Hashtable due to the fact that Hashtable implicitly checks for synchronization on each method call even in a single thread environment.
- HashMap allows storing null values, while Hashtable doesn’t.
- HashMap can be iterated by an Iterator which is considered as fail-fast . i.e. if any other thread modifies the map while iterating over it then a ConcurrentModificationException exception is thrown. However, Hashtable is iterated by an Enumerator which is not fail-fast.
- HashMap allows ordering and sorting its items through LinkedHashMap and TreeMap implementations, while this is not feasible with Hashtable.
In short, Hashtable is deprecated and replaced officially by ConcurrentHashMap, there is no reason for using it in new projects unless you’re working in a legacy code which doesn’t support HashMap (ideally there shouldn’t be an applications which just compile on versions < 1.2 as HashMap is introduced in JDK 1.2).