One of the common interview questions is “What are differences between Hashtable and HashMap“.When I started using them, I used any of them irrespective of their differences.Afterward I found noticeable differences between them which can affect your performance of the application. .Before we actually see differences, let me give you a brief introduction of both.
Java HashMap:
- HashMap in java
- How HashMap works in java
- hash and indexfor method in HashMap
- hashcode and equals method in java
- How to sort HashMap by keys and values
- Difference between HashMap and HashSet
- Difference between HashMap and Hashtable
- How to iterate over HashMap
HashMap
HashMap implements Map interface which maps a key to value. It is not synchronized and is not thread-safe. Duplicate keys are not allowed and null keys, as well as value, are allowed.
1 2 3 4 5 |
HashMap<Interger,String> employeeHashmap=new HashMap<Integer,String>(); employeeHashmap.put(1,"Arpit"); employeeHashmap.put(2,null); Â // will work fine |
Hashtable
Hashtable implements Map interface which maps key to value. It is synchronized and thread-safe. Duplicate keys are not allowed and the null key is not allowed.
1 2 3 4 5 |
Hashtable<Interger,String> employeeHashmap=new Hashtable<Integer,String>(); employeeHashmap.put(1,"Arpit"); employeeHashmap.put(2,null);  //not allowed and will throw NullPointer exception at run time |
Hashtable vs HashMap:
Parameter
|
Hashtable
|
HashMap
|
---|---|---|
ThreadSafe
|
Yes
|
No
|
Synchronized
|
Yes
|
No
|
Performance
|
Due to theadSafe and Synchronized,it is often slower than HashMap
|
In single threaded environment, it is much faster than Hashtable.So if you do not work in multi thread environment ,then hashMap is recommended
|
Null key
|
Do not allow
|
Allows null key as well as values
|
Fail fast
|
enumeration in hashtable is not fail fast
|
Iterator in hashMap is fail fast
|
Extends
|
It extends Dictionary class which is quite old
|
It extends AbstractMap class
|
Alternative
|
No alternative
|
You can use ConcurrentHashMap for multi thread environment
|
Some important points need to be discussed.
- Synchronized means only one thread can modify one table at one point of time. When any thread performs update operation on hashtable then it acquires lock on it and other threads have to wait for lock to be released.
- Fail-fast iterator means if one thread is iterating over hashmap and other thread trying to modify hashmap structurally it will throw ConcurrentModification Exception and fail immediately. Structurally modification means inserting or deleting elements that can change the structure of map.
Can we synchronize HashMap?
Yes, We can synchronized a HashMap also with the help of Collections.synchonizedMap(hashmap) so HashMap can be synchronized by
1 2 3 |
Map map=Collections.synchonizedMap(hashmap) |
Please go through core java interview questions for more interview questions.