In this article, we will discuss difference between HashMap and Hashtable classes in detail i.e.; HashMap v/s Hashtable
Hashtable is legacy class and based on hashcode of keys where keys are unique and it is exactly same as HashMap with few differences with respect to following points
- Synchronized methods
- Null key insertion
- Null value insertion
Lets us move on and discuss key differences between these 2 Map implemented classes
HashMap v/s Hashtable
|HashMap is introduced in collection framework in Java 1.2 version||Hashtable is a legacy class and introduced in Java 1.0 version|
|HashMap is NOT synchronized||Hashtable is synchronized|
|All methods of HashMap is NOT synchronized i.e.; it is not thread-safe||All methods of HashMap is synchronized i.e.; thread-safe|
|Multiple threads are allowed to access||Only one thread is allowed access; other threads has to wait to get access, after obtaining lock/monitor|
|Performance-wise, this is relatively high comparing with Hashtable, as there is no wait time||Performance-wise, this is relatively slow due synchronized methods as there is only one thread allowed to access, at any given point of time|
|NULL insertion allowed for both keys and values||NULL insertion is not allowed for both keys and values|
|Maximum of one NULL key and there is no upper limit for values||Simply, not allowed for both keys & values|
Note: both uses hash table data structure to store key-value pairs
When to use HashMap?
- HashMap stores key-value pairs which uses hashing technique to store key-value pairs where methods are NOT synchronized
- So, search operation is faster with multiple threads access
- So, if business requirement is to store key-value pairs for faster search operation or more number of search operation on the basis of keys; without concerning concurrent access of map
- Then, HashMap is the very apt choice
When to use Java Hashtable?
- This is exactly same as that of HashMap, but every methods is synchronized
- Performance-wise is relatively slower than comparing HashMap
- So, if business requirement is to store key-value pairs for faster search operation with synchronized access
- Then, Java Hashtable is preferred choice over HashMap
Happy Coding !!
Happy Learning !!