Difference between HashMap and HashTable in Java

 


Map is one of the important Interface in Java Collections and Maps contains key and value which always stores unique keys and values. Both HashMap and Hashtable implements Map interface and works based on hashing algorithm. 

Even HashMap and Hashtable implements Map interface but there are few important difference between these. Before using HashMap and Hashtable in application we need to know the functionality of both, by mistake if we select incorrect implementation class then it leads to lot of performance impact and error in our application. 

From JDK 1.4 onwards Hashtable included in Collection
Lets see few important difference between HashMap and Hashtable in Java.


Difference between HashMap and Hashtable.

  • First important difference between HashMap and Hashtable is, Hashtable is thread-safe (by default synchronized) and HashMap is not thread-safe.
  • HashMap allows null key and null value, but Hashmap won't allow null key and value which will give runtime NullPointerException.
  • As performance wise HashMap will be faster than Hashtable since its not synchronized. 
  • Iterator in HashMap class is a fail-fast iterator and enumerator in Hashtable is fail-safe and throw ConcurrentModificationException if any other Thread modifies.


Alternate for Hashtable:

If we need to use HashMap with thread-safe then we can convert HashMap to synchronized HashMap or we can for ConcurrentHashMap class. How to convert HashMap to synchronized HashMap have seen in our earlier tutorial.

Below are simple example for HashMap and Hashtable.

HashMap:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMap<String, String>();
  hm.put(null, null);
  hm.put("1", "one");
  System.out.println("Value : "+ hm.get(null));
  
  // Converting HashMap to Synchronized HashMap
  hm = Collections.synchronizedMap(hm);  
 }
}


Hashtable:


public  class MyTestClass {

 public static void main(String[] args) {
  
  Map<String, String> ht = new Hashtable<String, String>();
  
  // gives NullPointerException
  //ht.put(null, null);
  
  ht.put("1", "one");
  System.out.println("Value : "+ ht.get(null));
 }
}









No comments:
Write comments