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 !!