At entry level Java programmer, you can expect this interview question on Hashtable vs HashMap. Though the question becomes really easy when you know other concepts like how hashmap works, yet after getting a many queries from my blog readers who are preparing for or working at junior level, I have decided to summarize my knowledge on differences between HashMap
and a Hashtable
.
1. Differences between HashMap and Hashtable
1.1. Synchronization
Hashtable
is synchronized (i.e. methods defined inside Hashtable
), whereas HashMap
is not. If you want to make a HashMap
thread-safe, use Collections.synchronizedMap(map)
or ConcurrentHashMap
class.
Methods inside HashTable
are defined synchronized as below:
public synchronized boolean contains(Object obj){ ... } public synchronized boolean containsKey(Object obj){ ... } public synchronized Object get(Object obj){ ... } public synchronized Object put(Object obj, Object obj1){ ... } public synchronized Object remove(Object obj){ ... }
1.2. Null keys
Hashtable does not allow null keys or values. HashMap
allows one null key (other null keys will simply overwrite first null key) and any number of null values.
Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put(null, "value"); //OR hashTable.put("key", null); Output: Exception in thread "main" java.lang.NullPointerException at java.util.Hashtable.hash(Unknown Source) at java.util.Hashtable.put(Unknown Source) at test.core.MapExamples.main(MapExamples.java:12)
1.3. Legacy
Hashtable
is legacy class and was not part of the initial Java Collections Framework (later it was included in JDK 1.2). HashMap
is part of Collections since it’s birth. Also note that Hashtable
extends the Dictionary
class, which as the Javadocs state, is obsolete and has been replaced by the Map
interface in newer JDK versions.
//HashTable is defined as public class Hashtable extends Dictionary implements Map, Cloneable, Serializable {} //HashMap is defined as public class HashMap extends AbstractMap implements Map, Cloneable, Serializable {}
1.4. Fail-fast iterator
Iterator
in the HashMap
is fail-fast and throw ConcurrentModificationException
if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. The enumerator for the Hashtable is not fail-fast.
HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("key1", "value1"); hashMap.put("key2", "value2"); hashMap.put("key3", "value3"); hashMap.put("key4", "value4"); Iterator<String> iterator = hashMap.keySet().iterator(); while(iterator.hasNext()){ iterator.next(); iterator.remove(); System.out.println(hashMap); } Output: {key3=value3, key2=value2, key1=value1} {key2=value2, key1=value1} {key1=value1} {}
1.5. contains() method
Finally, Map fixes a minor deficiency in the Hashtable
interface. Hashtable
has a method called “contains()” (along with “containsValue()” and “containsKey()“), which returns true if the Hashtable
contains a given value. Given its name, you may expect this method to return true if the Hashtable
contained a given key, because the key is the primary access mechanism for a Hashtable
.
The Map
interface eliminates this source of confusion by removing this method to and has only “containsValue()” and “containsKey()“.
public boolean containsKey(Object obj) {...} public boolean containsValue(Object obj) {...}
2. When to use HashMap and Hashtable
There is hardly any job which HashMap or it’s related classes (i.e. LinkedHashMap
or ConcurrentHashMap
) can not do which HashTable does. So, there is no good reason to use Hashtable
in new code you write. Always prefer to use HashMap over HashTable.
It’s really hard to go deeper and deeper inside this list. As soon as you are able to understand above differences, you are good to use both the classes (infact only HashMap you should use). For me, analyzing beyond above points is simply waste of time. So, I am stopping here.
Happy Learning !!
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface. Thanks for sharing this difference.
Hi,
As I have seen the implementation of both HashMap & HashTable, I found containsKey() & containsValue() are available in both the implementations. Then how the 5th difference is valid.
Updated the point to remove confusion. Thanks for taking it up.
Hi,
I am using Google’s Multimap to store multiple values against the same key but facing the below prblm:
Assuming my key is: A,B
Assuming values mapped with above key is: Apple,Orange.
Now when I try to say: multiMap.get(B,A), it still returns me Apple,Orange.
Ideally it should not return since the original key is A,b and not B,A. Somehow , it does not care about the ordering of the keys. Any suggestions to the above if you have encountered this before?
It’s really strange and I doubt that you are doing something unusual. Can you please try a sample code (just put the values, and get it back) and post the code here? It will help in understanding the problem more clearly.
HashMap makes absolutely no guarantees about the iteration order. I want to know Hashtable also does not gurantee the iteration of Order?
NO, HashTable also does not preserve the ordering of elements. Only EnumMap and LinkedHashMap are Map implementations which can preserve the ordering (in my knowledge).
Hello Sir, i just want to know that how we can get index location in an Hash table.
Thanks for great post, but you Hastable convention is wrong “Suggestion regarding usage of HashMap vs HashTable”. Please replace the “T” into lower case.
Thanks for pointing out the typo. Corrected it.
It is said in the article that hash table is thread safe which means no concurrent modification problem. Then you talked about fail fast for hash table..I am confused
Fail fast has noting to do with thread-safety. Both are completely different concepts.
Why Hashtable class does not allow null key and null values? hash value for “null” is zero and HashMap is storing null key (and corresponding value) in the 0th location. why hashtable is not using this ? Is there any specific reason ?
No Specific reason. It simply check if key is null, the throw the NullPointerException. And for value, it simply tries to do some operation which which result into NullPointerException.