Difference between HashMap and a Hashtable

If you are preparing for a job as entry level java programmer, you can expect this interview question. 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 this particular question i.e. difference between HashMap and a Hashtable.

Differences between HashMap and a Hashtable

1) 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){ ... }

2) 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)

3) 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 {}

4) 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}
{}

5) Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called “contains()“, 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 renaming the method to “containsValue()” and “containsKey()“.

public boolean containsKey(Object obj) {...}
public boolean containsValue(Object obj) {...}

Suggestion regarding usage of HashMap vs 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.

If interviewer is not satisfied with above differences, let me assure you he will never be with whatever you tell him.

Happy Learning !!

Ads by Google

11 thoughts on “Difference between HashMap and a Hashtable”

  1. 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?

    1. 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.

  2. HashMap makes absolutely no guarantees about the iteration order. I want to know Hashtable also does not gurantee the iteration of Order?

    1. 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).

  3. Thanks for great post, but you Hastable convention is wrong “Suggestion regarding usage of HashMap vs HashTable”. Please replace the “T” into lower case.

  4. 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

      1. 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 ?

        1. 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.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Want to ask any question? Or suggest anything?