Signup/Sign In

Difference Between Hashmap and Hashtable in Java

HashMap and Hashtable are both used to represent a collection of items represented by a Key, Value> pair. Each Key-Value pair is referred to as an Entry object. The object of HashMap and Hashtable refers to the collection of Entries. A collection's keys must be one-of-a-kind or unusual.

The distinction between HashMap and Hashtable is that HashMap implements the Map interface specifically, while Hashtable extends the Dictionary class (old class) to implement the Map interface. Another significant distinction is that HashMap objects are unsynchronized, but Hashtable objects are synchronised.

What is a HashMap in Java?

HashMap is a class that extends the AbstractMap class that utilises the hash table to implement the Map interface. The HashMap object is a collection/set of Key, Value> pairs, each of which is mapped to a specific value. Because they are used to retrieve the value, keys in a collection must be unique. A collection's values, on the other hand, may be replicated.

Example of HashMap in Java

// Java program to illustrate HashMap class of java.util
// package
 
// Importing HashMap class
import java.util.HashMap;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Create an empty hash map by declaring object
        // of string and integer type
        HashMap<String, Integer> map = new HashMap<>();
 
        // Adding elements to the Map
        // using standard put() method
        map.put("vishal", 10);
        map.put("sachin", 30);
        map.put("vaibhav", 20);
 
        // Print size and content of the Map
        System.out.println("Size of map is:- "
                           + map.size());
 
        // Printing elements in object of Map
        System.out.println(map);
 
        // Checking if a key is present and if
        // present, print value by passing
        // random element
        if (map.containsKey("vishal")) {
 
            // Mapping
            Integer a = map.get("vishal");
 
            // Printing value for the corresponding key
            System.out.println("value for key"
                               + " \"vishal\" is:- " + a);
        }
    }
}

Output


Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:- 10

What is a Hashtable in Java?

Hashtable extends the Dictionary class, which is a heritage class that has been reengineered to support the Map interface. The data structure of the Hashtable is a hash table. Hashtables are similar to HashMaps in that the Hashtable object refers to a collection of entries, each of which is a pair of Key and Value>.

On the other hand, although all of the keys in a collection must be unique, the values may be replicated. The keys are utilised to determine the hash code value, which determines the index in which the Key, Value> pair will be kept in a hash table. Neither a key nor a value in a hash table may yield a Null pointer.

Example of Hashtable in Java

import java.util.*;  
public class Hashtable2 {  
   public static void main(String args[]) {  
  Hashtable<Integer,String> map=new Hashtable<Integer,String>();        
     map.put(100,"Amit");    
     map.put(102,"Ravi");   
     map.put(101,"Vijay");    
     map.put(103,"Rahul");    
     System.out.println("Before remove: "+ map);    
       // Remove value for key 102  
       map.remove(102);  
       System.out.println("After remove: "+ map);  
   }      
}  

Output


Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
After remove: {103=Rahul, 101=Vijay, 100=Amit}

Key Difference Between Hashmap and Hashtable in Java

HashMap HashTable
  • The HashMap class extends the AbstractMap class and implements the Map interface.
  • The Hashtable inherits from the Dictionary Legacy class, however it has been re-engineered to support the Map interface.
  • The HashMap object is threaded unsafe since it is unsynchronized.
  • Hashtable is synchronised, hence the Hashtable object is thread safe Keys/Value.
  • A key can only return Null once, whereas a value may return Null several times.
  • A key cannot return Null because it is used to acquire the hash code, which will be used as an index in the hash table, and a value cannot return Null because it is used to obtain the hash code, which will be used as an index in the hash table.
  • HashMap has a capacity of 16 by default.
  • Hashtable's default starting capacity is 11.
  • Iterator traverses the HashMap.
  • Hashtable, like Map, does not natively provide Iterator for traversal and instead utilises Enumerator.

FAQs

1. Which is faster HashMap or Hashtable?

Ans.- HashMap is not synchronized, therefore it's faster and uses less memory than Hashtable. Generally, unsynchronized objects are faster than synchronized ones in a single-threaded application.

2. What is the difference between HashMap Hashtable and HashSet?

Ans.- Hashmap allows one null for key and multiple nulls for values. HashSet can have a single null value. Hashtable does not allow null for the key as well as for value.

3. Is Hashtable synchronized?

Ans.- HashMap is non-synchronized. It is not thread-safe and can't be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.

4. Why null key is allowed in HashMap?

Ans.- In order to successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can't implement these methods.



About the author:
Adarsh Kumar Singh is a technology writer with a passion for coding and programming. With years of experience in the technical field, he has established a reputation as a knowledgeable and insightful writer on a range of technical topics.