HashMap vs Hashtable in Java
Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, the main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. This means you cannot use HashMap in a multi-threaded Java application without external synchronization. Another difference is HashMap allows one null key and null values but Hashtable doesn't allow null key or values. Also, the thread-safety of the hash table is achieved using internal synchronization, which makes it slower than HashMap.
By the way, the difference between HashMap and Hashtable in Java is one of the frequently asked in core Java interviews to check whether the candidate understands the correct usage of collection classes and aware of alternative solutions available.
Along with How HashMap internally works in Java and ArrayList vs Vector, this is one of the oldest questions from the Collection framework in Java. Hashtable is a legacy Collection class and it's there in Java API for a long time but it got refactored to implement Map interface in Java 4 and from there Hashtable became part of the Java Collection framework.
Hashtable vs HashMap in Java is so popular a question that it can top any list of Java Collection Interview Questions. You just can't afford to prepare HashMap vs Hashtable before going to any Java programming interview. In this Java article, we will not only see some important differences between HashMap and Hashtable but also some similarities between these two collection classes. Though for complete preparation,
Let's first see How different they are:
Though both Hashtable and HashMap are data-structure based upon hashing and implementation of Map interface, the main difference between them is that HashMap is not thread-safe but Hashtable is thread-safe. This means you cannot use HashMap in a multi-threaded Java application without external synchronization. Another difference is HashMap allows one null key and null values but Hashtable doesn't allow null key or values. Also, the thread-safety of the hash table is achieved using internal synchronization, which makes it slower than HashMap.
By the way, the difference between HashMap and Hashtable in Java is one of the frequently asked in core Java interviews to check whether the candidate understands the correct usage of collection classes and aware of alternative solutions available.
Along with How HashMap internally works in Java and ArrayList vs Vector, this is one of the oldest questions from the Collection framework in Java. Hashtable is a legacy Collection class and it's there in Java API for a long time but it got refactored to implement Map interface in Java 4 and from there Hashtable became part of the Java Collection framework.
Hashtable vs HashMap in Java is so popular a question that it can top any list of Java Collection Interview Questions. You just can't afford to prepare HashMap vs Hashtable before going to any Java programming interview. In this Java article, we will not only see some important differences between HashMap and Hashtable but also some similarities between these two collection classes. Though for complete preparation,
Let's first see How different they are:
Difference between HashMap and Hashtable in Java
Both HashMap and Hashtable implements Map interface but there is some significant difference between them which is important to remember before deciding whether to use HashMap or Hashtable in Java. Some of them are thread-safety, synchronization, and speed. here are those differences :
1.The HashMap class is roughly equivalent to Hashtable, except that it is non-synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not be shared between multiple threads without proper synchronization. Java 5 introduces ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.
4. One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower than HashMap if used in Single threaded environment. So if you don't need synchronization and HashMap are only used by one thread, it outperforms Hashtable in Java.
5. HashMap does not guarantee that the order of the map will remain constant over time.
If you are preparing this question as part of your Java interview preparation, I suggest preparing every important topic as given in Programming Interviews Exposed. It covers basics, core java, threads, a framework like Spring and Hibernate and many others key topics.
HashMap and Hashtable : note on Some Important Terms
1)Synchronized means only one Thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
2) Fail-safe is relevant from the context of iterators. If an Iterator or ListIterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
3) Structurally modification means deleting or inserting element which could effectively change the structure of the map.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
Also, here is one more table which shows more differences between HashMap and Hashtable in Java:
In Summary, there are significant differences between Hashtable and HashMap in Java e.g. thread-safety and speed and based upon that only use Hashtable if you absolutely need thread-safety if you are running Java 5 consider using ConcurrentHashMap in Java.
Other Java Collection tutorials you may like
How to sort a Map by keys and values in Java? (tutorial)
How to sort an ArrayList in ascending and descending order in Java? (tutorial)
Difference between ArrayList and HashSet in Java? (answer)
The difference between TreeMap and TreeSet in Java? (answer)
The difference between HashMap and ConcurrentHashMap in Java? (answer)
The difference between HashMap and LinkedHashMap in Java? (answer)
The difference between Hashtable and HashMap in Java? (answer)
The difference between HashSet and TreeSet in Java? (answer)
The difference between ArrayList and LinkedList in Java? (answer)
The difference between Vector and ArrayList in Java? (answer)
Difference between EnumMap and HashMap in Java
The difference between TreeMap and TreeSet in Java? (answer)
The difference between HashMap and ConcurrentHashMap in Java? (answer)
The difference between HashMap and LinkedHashMap in Java? (answer)
The difference between Hashtable and HashMap in Java? (answer)
The difference between HashSet and TreeSet in Java? (answer)
The difference between ArrayList and LinkedList in Java? (answer)
The difference between Vector and ArrayList in Java? (answer)
Difference between EnumMap and HashMap in Java
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment.
31 comments :
what about ConcurrentHashMap? What is the difference?
Hi Fedhie, ConcurrentHashMap is new addition in Java collections suite and best suited for situations where number of readers outnumber number of writers in a big way. Since concurrent read is allowed it improves performance significantly.
Thanks
Javin
Hi Anonymous thanks you liked it you can also see How HashMap works in Java , to know more about HashMap interview questions.
Synchronizing a hashmap is possible but rather a pain because that is what the hashtable is there... But, synchronizing manually can be risky and at times lead to the most dreaded deadlocks. You can know more about "Synchronization & Deadlocks" here .
Such a nice tutorial ....
can you care to explain difference bet fail-fast and fail-safe iterator on hashtable and hashmap , which one uses what, also hashmap is better or hashtable what is your opinion
Hi Anonymous 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 while in fail-safe iterator Iterations is done on copy of collection object instead of original e.g. in case of CopyOnWriteArraylist. iterator of hashmap is fail-fast and hashtable doesn't have any iterator that is another difference between hashmap and hashtable.
here are some more differences between hashtable and hashmap
1) hashtable extends Dictionary interface which is quite old while hashmap extends Map interface.
2) hashtalbe doesn't have counterpart like ConcurrentHashMap.
3) another important difference between hashtable and hashmap is , hashtable is less secure than hashmap because of Enumeration it uses. while hashmap uses iterator which prevents Concurrent Modification of HashMap, which is not possible in case of hashtable.
4) stay out of hashtable use hashmap instead.
wow Anonymous got more differences between hashtable and hashmap :)
I think key difference between hashmap and hastable is what you mentioned about Iterator and Enumeration , as Iterator being fail-fast beccomes natural choice over enumeration.
correct, though both hashtable and hashmap are older than new concurrenthashmap iterator and enumeration is key point.I would suggest to leave behind both hashmap and hashtable and move forward to concurrenthashMap.
Thanks Nagesh for your comment and good to know that you like this hashtable vs hashmap tutorial. you may also like Difference between ArrayList and Vector in java
iterator can be implemented for hashtable also
from Java4 I guest hashtable is also part of collection framework along with Vector. with the age of ConcurrentHashMap, does Hashtable still holds value ?
So it was it Hashtable() instead of HashTable() or something...
Can you please put a feature and performance comparison between
1. HashMap vs ConcurrentHashMap
2. HashMap vs Hashtable
3. HashMap vs LinkedHashMap
4. Hashtable vs ConcurrentHashMap
5. Hashtable vs LinkedHashMap and
6. ConcurrentHashMap vs LinkedHashMap
that would be simply great. Also if you could share when to use Hashtable, HashMap, ConcurrentHashMap and LinkedHashMap, that would be amazing, looking forward to see these comparison.
Hi
We can synchronize Map object using Collections.synchronizedMap(mapObj)...
Then
1) what is difference for map object(after synchronize using synchronizedMap method) and hashtable object?
2) Will be there any difference in synchronization using the method and by default the class as synchronized..
Hi
For getting the synchronized map the method name is collections.synchronizedMap() not synchronizeMap()
Hi,
what is the difference between synchronized hash-map and hash table?
I don't see any difference here but interviewer asked this quest ion.Can some one please explain me?
hash map allows null as values in key which is not true in case of hash table.
In a web application can we use HashMap. instead of HashTable.
If the answer is HashMap. then How?
In an webapplication are there not multiple thread trying to access the servlet or the EJB? How is it safe to use HashMap?
There are several differences between HashMap and Hashtable in Java:
Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
I think that this phrase is wrong,
"3. Another significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException ... "
So if the enumerator is not fail-fast, is fail-safe, and will not thrown an exception, right? maybe I'm missing something in the middle.
@makam, actually that true, Iterator of HashMap throws ConcurrentModificationException when HashMap is modified after iteration begun but Enumeration doesn't throw that exception.
Hello
@Javin, If Enumeration doesn't throw that exception then it will update the concurrent modification? or prevent it? what it will do.. Please explain..
hi everyone,
I am starting to learn about java but I need to know about a HashMap in java, actually, this is problem difficult because If you want to understand anything i think we should test program. It's help have look good better. I think I will remember best. So thanks a lot, I am try read all comment of friends in here. It's great for me.
@Anonymous, if you are looking for some good examples on HashMap then I suggest you to take a look at this tutorial, 10 examples of HashMap in Java. It's a great guide about using HashMap, particularly for anyone like you who wants to know more about HashMap.
Hi Javin,
I gotta bit of confusion between enumeration and iterator, few folks on the internet mentioning Enumeration is not fail-safe. But actually when i tried to do structural changes to hashtable, it simply allowed the changes to be made without any error just like CHM. Can you please explain me why?
I am having a problem grasping that remove()is O(1)in both the Hashset and LinkedHashset. I understand that the remove() for a hashset is O(1) ut in a linkedhashset, my understanding is that it is o(1) to determine that the Object is in the set and then o(n)to search for the order that the object was added which is o(n).
As some other person has already mentioned you are describing differences between fail-safe and fail-fast wrong in this article. Fail-fast means throwing ConcurrentModificationException
Very useful article.
One thing want to mention, image which you have given for comparison(for synchronization) in that it should be Collections but its Collection in the image.
Post a Comment