HashMap Vs HashTable

Hashmap vs Hashtable

HashMap Vs HashTable in Java

Are you preparing for an interview for a Java profession? You must understand the differences between HashMap and HashTable as it is an important interview question for any Java professional to kickstart the career. Though both HashTable and HashMap store key-value pairs and implements the same Java interface: java.util.Map, they differ with their usage and working.

There are two interfaces namely Map and Set in Java. A Map is used to map keys to objects (one object set to another). A Set is just a collection of objects and has no other structures.  Both HashMap and HashTable implements Map whereas Set is implemented only by HashSet. All the three: HashTable, HashKey, and HashSet use hashing technique for objects or keys.

Let us discuss the differences between the HashTable and HashMap classes in this section.

Thread Safe / Synchronization:

HashMap is not threaded safe and not synchronized. HashTable, on the other hand, is synchronized and thread safe. If you are doing a multithreading task, it is better to use HashTable and HashMap works best for non-threading or individual applications that are not synchronized. Multiple threads can access HashMap and process it simultaneously. HashTable, on the other hand, cannot be accessed by more than a thread at a time (synchronization). A lock is acquired by the thread which is currently using the HashTable and all the other threads are made to wait until the thread completes its operation and releases the lock.

Performance:

It is a common rule that unsynchronized applications run much faster than synchronized applications. Thus, HashMap is faster and uses much lesser memory space when compared to HashTable. HashTable must be avoided as it is a legacy class and the performance is slower than HashMap. Method level synchronizations cannot be removed from HashTable (until you break the code) and thus the HashMap was developed in the future.

Collection Framework:

Initially, HashTable did not belong to Collection Framework but after getting retrofitted for implementing java.util. Map interface, it is added to the Collection Framework. HashMap belongs to the Collection Framework from the beginning.

Null Values and Null Keys:

Hashtable never allows any null values and null keys in its objects, while Hashmap allows multiple null values and only a single null key value.

Order:

Insertion order is maintained by HashMap as it uses LinkedHashMap for keeping track of insertion order and TreeMap for sorting key mappings in the ascending order. Hashtable never maintains any order and does not maintain key mappings in ascending or descending order.

Iteration:

Hashmap objects use an iterator for traversing or iterating and HashTable uses both iterator and enumerator for iterating the object values. Other than vector class, HashTable is the only class that uses enumerators for traversing values. HashMap iterators are fail-fast, while HashTable iterators are not fail-fast.

Exception:

HashMap throws an exception called ConcurrentModificationException when an outside Thread tries to modify map structure by removing or adding any of its elements except remove() method. If iterator.next() is called, ConcurrentModificationException is thrown immediately after iterator creation and next() method call.

Inheritance:

HashTable is inherited from Dictionary class and HashMap is inherited from the AbstractMap class.

Legacy:

HashTable is a legacy class but HashMap is introduced only from JDK 1.2 and it is a new class. HashTable is in practice since Java version 1.2 and HashMap since the Java version 1.5.

Let us consider a Java program to understand HashMap and HashTable better. This example shows a simple difference: the HashMap accepts one null value whereas HashTable does not accept any null values.

Example Java program demonstrating HashTable and HashMap

// An example Java program for demonstrating HashTable and HashMap
import java.util.*;
import java.io.*;
import java.lang.*;
class Sample
{
public static void main(String args[])
{
//hashtable
Hashtable<Integer,String> hasht=new Hashtable<Integer,String>();
hasht.put(500,"Abi");
hasht.put(501,"Ragul");
hasht.put(502,"Raja");
hasht.put(503,"Mani");
System.out.println("******Hash table******");
for (Map.Entry mm:hasht.entrySet()) {
System.out.println(mm.getKey()+" "+mm.getValue());
}

//----------------hashmap--------------------------------

HashMap<Integer,String> hashm=new HashMap<Integer,String>();
hashm.put(500,"Ajith");
hashm.put(504," ");  //One null value is allowed in HashMap
hashm.put(501,"Sanjay");
hashm.put(502,"Vimal");
System.out.println("********Hash Map******");
for (Map.Entry mm:hashm.entrySet()) {
System.out.println(mm.getKey()+" "+mm.getValue());
}
}
}

Output:

******Hash Table******

500 Abi

501 Ragul

502 Raja

503 Mani

******Hash Map********

500 Ajith

504

501 Sanjay

502 Vimal

Differentiation Between HashTable and HashMap

Features

HashTable

HashMap

Synchronization Synchronized Not Synchronized
Order No order is guaranteed Maintains order
Collection Framework Recent member Old member
ConcurrentModicationException No exception Throws
Iterator Not Fail-fastest iterator and enumerator for values traversal Fail-fastest iterator for values traversal
Performance Slow Fast
Legacy Yes No
Superclass Dictionary class AbstractMap class
Java Version since JDK 1.2 JDK 1.5

Similarities Between HashTable and HashMap

Map interface:

Both these classes, HashMap and HashTable implements the same Map interface.

Hashing Technique:

Both HashTable and HashMap uses the hashing mechanism for working.

Order of Insertion:

Neither HashMap nor HashTable guarantees a constant order of map over time. If you want the order of objects to remain constant with time, use LinkedHashMap.

get() and put() methods:

Constant time performance is provided by both HashTable and HashMap assuming a uniform distribution of objects over a period of time.

Duplicate values:

Duplicate values are allowed in both HashMap and HashTable. 

Selecting HashTable versus HashMap

  1. The major difference between HashTable and HashMap is synchronization. For thread-safe operations, HashTable can be used as all the methods of HashTable are synchronized as it’s a legacy class. HashMap can be explicitly synchronized and for multithreaded applications, we can use ConcurrentHashMap.
  2. Non-threaded applications use HashMap over HashTable without a doubt. The synchronized operations must be avoided until there is a need as the performance gets degraded by synchronization.

Conclusion:

HashMap is not synchronized while HashTable is synchronized. HashTable is thread-safe while HashMap is not thread-safe. Iterator type in HashMap is fail-fast whereas it is fail-safe in HashTable. Performance is slow in HashTable, while fast in HashMap. HashMap supports any number of null values and one null key value whereas HashTable has no permission for null values and null keys. AbstractMap is the superclass of HashMap and Dictionary is the superclass of HashTable.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Looking for Online Training