HashMap vs Hashtable in Java: Difference Between The Two

HashMap vs Hashtable in Java: Difference Between The Two

5 mins read539 Views Comment
Jaya
Jaya Sharma
Assistant Manager - Content
Updated on Dec 4, 2023 17:44 IST

Hashtable and HashMap are both used for implementing the Map interface. They use hashing techniques to store unique keys. However, the main difference between the two is that Hashtable is synchronized whereas HashMap is not.

2022_12_MicrosoftTeams-image-101.jpg

In this article on HashMap vs Hashtable, we will discuss HashMap and Hashtable individually. We will also understand the difference between hashmap and hashtable as well.

Table of Contents

HashMap vs Hashtable

Differences between HashMap and Hashtable are as per the tabular format:

Parameters  HashMap Hashtable
Explanation It is a nap implementation that uses a Hashtable for storage Legacy Map implementation that uses a hashtable for storage
Inheritance Extends AbstractMap  Extends Dictionary 
Use Cases General Purpose Map Implementation Thread Safe and Legacy Map Implementation 
Preferred for Implementation of New Code Preferred since it is faster and more flexible Not preferred since it is slower. Use ConcurrentHashMap instead.
Insertion and Mapping Order Maintained No particular order
Thread Safety No Yes
Suitability for Multi-threaded Environment No, since it requires external synchronization Yes, since it has built-in synchronization
Null Keys Allowed Not allowed
Null Values Allowed Not allowed
Performance Faster  Slower 
Iterator Fail fast Not fail fast

Before moving further to understand these terms individually, let us try understanding the difference between the two.

 

What is HashMap in Java?

In Java, HashMap is a part of collection classes in Java. It is a table-based implementation that extends AbstractMap class to implement the Map interface. HashMap is unsynchronised in nature and allows only one null key object but multiple null values. 

The following points brief about Java HashMap:

  • Allows null values and null key
  • Uses inner Node <K,V> to store map entries
  • Stores entries in multiple single linked lists such as bins and buckets
  • Uses hashCode() and equals() methods on keys for put and get operations, thus providing good implementation of these methods
  • It is not thread-safe and unsuitable for a multi-thread environment

Explore free Java courses

Program Displaying HashMap in Java

Following is an example of a Java program consisting of HashMap:


  
// Java program for llustrating HashMap class of java.util
import java.util.*;
public class HashMapSample{
public static void main(String args[]){
HashMap<integer,string> map=new HashMap<integer,string>();//Creating a HashMap
map.put(1,"Pineapple"); //Put elements in the Map
map.put(2,"Berries");
map.put(3,"Apple");
map.put(4,"Oranges");
System.out.println("Iterating the Hashmap:");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
</integer,string></integer,string>
Copy code

Output:


 
Iterating the Hashmap:
1 Pineapple
2 Berries
3 Apple
4 Oranges
Copy code

What is Hashtable in Java?

Hashtable in Java is an array of a list that implements Hashtable to map keys to values. It inherits the dictionary class to implement Map interface. While using Hashtable, you need to specify an object to be used as a key and the value that you want to be linked to that key. This key is then hashed and the resultant hash code is used as index at which value is stored within the table. Hashtable has the following features:

  • Contains unique elements
  • Integrated into collections framework 
  • It does not allow null value or key
  • It is synchronized
  • The default capacity of the Hashtable class is 11 while loadFactor is 0.75

Program displaying Hashtable in Java

The following Java program illustrates the use of Hashtable:


 
import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableSample {
public static void main(String[] args) {
Enumeration names;
String key;
// Creating the Hashtable
Hashtable<string, string=""> hashtable =
new Hashtable<string, string="">();
// Adding Key and Value pairs to the Hashtable
hashtable.put("Key1","Raghav");
hashtable.put("Key2","Rajeev");
hashtable.put("Key3","Puneet");
hashtable.put("Key4","Rishabh");
hashtable.put("Key5","Megha");
names = hashtable.keys();
while(names.hasMoreElements()) {
key = (String) names.nextElement();
System.out.println("Key: " +key+ " & Value: " +
hashtable.get(key));
}
}
}
</string,></string,>
Copy code

Output:


 
Key: Key4 & Value: Rishabh
Key: Key3 & Value: Puneet
Key: Key2 & Value: Rajeev
Key: Key1 & Value: Raghav
Key: Key5 & Value: Megha
Copy code

Similarities between Hashmap and Hashtable

While Hashmap and Hashtable differ in a number of ways, they do come with some similarities. 

  • Both HashMap and Hashtable store data in value and key form.
  • They are the collections that implement Map interface.
  • HashMap and Hashtable are both types of data structures.
  • The map interface is hashed and mapped using HashMap as well as Hashtable.
  • Both use hashing techniques for storing unique keys.

While we have already discussed the difference between HashMap and Hashtable, we will now try to explore which one to choose and when to choose between hashmap and hashtable in Java. 

Explore data structures and algorithms courses

HashMap Vs Hashtable: Which one to prefer?

The choice between HashMap and Hashtable in Java depends on several factors such as thread-safety, performance, and legacy code compatibility. Here's a detailed comparison to help you decide when to use each:

HashMap

  1. Non-Thread Safe: HashMap is not synchronized and is not thread-safe. This makes it unsuitable for multi-threaded environments where it might be accessed by multiple threads simultaneously. However, it offers better performance in single-threaded or read-only scenarios due to the absence of synchronization overhead.
  2. Null Values and Keys: HashMap allows one null key and multiple null values, which can be useful in certain scenarios where you need to represent the absence of a value.
  3. Performance: It generally provides better performance in scenarios not requiring synchronization.
  4. Use Cases:
    • Single-Threaded Environments: Ideal for applications where thread safety is not a concern.
    • Read-Intensive Operations: Suitable for scenarios with a high number of read operations and fewer modifications.
    • Storing Null Values: When you need to store null keys or values.

Hashtable

  1. Thread-Safe: Hashtable is synchronized. Every method is wrapped with a synchronized block, which ensures thread safety. However, this comes at the cost of performance, making it slower compared to HashMap in environments where thread safety is not a concern.
  2. No Null Values or Keys: It does not allow null keys or values, which might be a limitation in certain applications.
  3. Legacy Class: It is a legacy class in Java. While it's still used in legacy applications, newer codebases typically prefer HashMap or ConcurrentHashMap.
  4. Use Cases:
    • Legacy Applications: Suitable for older Java applications that were originally designed with Hashtable.
    • Simple Thread-Safe Operations: For basic thread-safe operations in applications where performance is not the main concern.

HashMap Vs Hashtable: Which one to prefer?

  • Prefer HashMap when:
    • You are working in a non-threaded environment, or synchronization is handled externally.
    • You need to store null values or keys.
    • Performance is a critical factor, and thread safety is not a concern.
  • Prefer Hashtable when:
    • You are working with legacy code that already uses Hashtable.
    • You require a simple, thread-safe map implementation and do not need high concurrency or null support.

While you can prefer either HashMap or Hashtable in Java depending on your requirement, you can prefer ConcurrentHashMap for two cases. First, you can use it in case of multi-threaded applications where high performance and concurrency are required. Second, you can use it in situations where you would use Hashtable but need better performance and more sophisticated thread-safety features.

About the Author
author-image
Jaya Sharma
Assistant Manager - Content

Jaya is a writer with an experience of over 5 years in content creation and marketing. Her writing style is versatile since she likes to write as per the requirement of the domain. She has worked on Technology, Fina... Read Full Bio