What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
My small contribution :
First and most significant different between
Hashtable
andHashMap
is that,HashMap
is not thread-safe whileHashtable
is a thread-safe collection.Second important difference between
Hashtable
andHashMap
is performance, sinceHashMap
is not synchronized it perform better thanHashtable
.Third difference on
Hashtable
vsHashMap
is thatHashtable
is obsolete class and you should be usingConcurrentHashMap
in place ofHashtable
in Java.
Hashtable:
Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException
if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.
Example :
import java.util.Map;
import java.util.Hashtable;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states= new Hashtable<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); //will throw NullPointerEcxeption at runtime
System.out.println(states.get(1));
System.out.println(states.get(2));
// System.out.println(states.get(3));
}
}
HashMap:
HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable
, because it is unsynchronized
.
Example:
import java.util.HashMap;
import java.util.Map;
public class TestClass {
public static void main(String args[ ]) {
Map<Integer,String> states = new HashMap<Integer,String>();
states.put(1, "INDIA");
states.put(2, "USA");
states.put(3, null); // Okay
states.put(null,"UK");
System.out.println(states.get(1));
System.out.println(states.get(2));
System.out.println(states.get(3));
}
}
Hashtable
is considered legacy code. There's nothing about Hashtable
that can't be done using HashMap
or derivations of HashMap
, so for new code, I don't see any justification for going back to Hashtable
.
For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.
1.Hashmap
and HashTable
both store key and value.
2.Hashmap
can store one key as null
. Hashtable
can't store null
.
3.HashMap
is not synchronized but Hashtable
is synchronized.
4.HashMap
can be synchronized with Collection.SyncronizedMap(map)
Map hashmap = new HashMap();
Map map = Collections.SyncronizedMap(hashmap);
HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.