Programs

Differences Between HashMap and HashTable in Java

If you’re learning about Java and its applications, you must have come across HashMap and HashTable. Both of them are among the most important classes in the Java Collection framework. You’ll be using them extensively while developing with Java, which is why it’s vital to understand their differences. 

Check out our free courses to get an edge over the competition

In the following points, we’ll cover the HashTable vs HashMap topic in detail and explain the distinctions between the two: 

What is HashMap?

HashMap has been in Java’s collection since the introduction of Java 1.2. It allows you to perform basic implementations of the Map interface of Java. HashMap stores data in (Key, Value) pairs, and to access them, you’ll have to use an index of another type, such as an integer. 

Here, you use one object as a key (index) for another object (value), hence the use of (key, value) pair. If you add a duplicate key, it will replace the element of the corresponding key. 

Check out upGrad’s Advanced Certification in Blockchain

Explore Our Software Development Free Courses

Features of HashMap

To understand the distinctions between HashTable vs HashMap, first, you must understand their features. It would make you familiar with the basics of both of them. HashMap has the following features:

  • It is part of java.util package.
  • It extends an abstract class AbstractMap that provides an incomplete implementation of the Map interface.
  • Along with implementing Map interface, it also implements Serializable and Cloneable interfaces. 
  • It allows duplicate values but doesn’t allow duplicate keys. This means one key can’t have more than one value, but multiple keys can have a single value. 
  • You can use the null key only once in a HashMap, but you can use multiple null values. 
  • It makes no guarantees about the order of the map, particularly whether or not the order would remain constant over time. HashMap is nearly similar to HashTable but is unsynchronised. 
  • HashSet uses HashMap internally.

In-Demand Software Development Skills

Check out upGrad’s Advanced Certification in DevOps 

What is HashTable?

You use the HashTable class to implement a hash table that maps keys to values. Here, you can use non-null objects as a key or as a value. Keep in mind that to store and retrieve objects from a hashtable successfully, the objects you used as keys must implement the hashCode method and the equals method. 

A hashtable stores data in an array format, and every data value has a unique index value. This allows you to access particular data quite quickly if you know the required index. 

Features of HashTable

HashTable has its peculiar features, just like HashMap. However, these features make it unique and different from HashMap in many respects: 

  • HashTable is quite similar to HashMap but is synchronised.
  • It stores key-value pairs in a hash table.
  • Here, you specify an object used as a key and the value you want to associate to the same. Then you hash the key and use the generated hash code as the index where you store the value within the table. 
  • The default capacity of the Hashtable class is 11, and the load factor is 0.75.
  • HashMap doesn’t offer Enumeration, whereas Hashtable offers not fail-fast Enumeration. 

Similarities in HashMap and HashTable

We may better understand the difference between HashMap and HashTable after we are familiar with fundamental ideas and the similarities between HashMaps and Hash Tables.

  • In Java, neither HashMap nor HashTable maintains insertion order.
  • The Java.util.Map interface is implemented by both HashMap and HashTable.
  • The complexity offered by methods of both HashTable and HashMap is the same in Java:
Operation Worst Case Best Case
put(K key, V value) O(n) O(1)
get(Object key) O(n) O(1)

Differences Between HashMap and HashTable

Now that you know the particular highlights of HashMap and HashTable, we’ll now compare them and see the prominent differences between the two:

HashMap HashTable
It is non-synchronised. You can’t share many threads here without using proper synchronisation code because it is not thread-safe.  It is synchronised. You can share it with many threads because it is thread-safe.
It inherits the AbstractMap class. It inherits the Dictionary class. 
Here, the Iterator is fall-fast.  In HashTable, the Enumerator is not fall-fast.
The Iterator traverses the HashMap. The Enumerator and Iterator traverse the HashTable. 
You can make a HashMap synchronised by calling the code
Map m = Collections.synchronisedMap(hashMap);
Hash Tables are synchronised internally, and you can’t unsynchronised them with any code. 
It is quite fast.  It is relatively slower than HashMap.
HashMap is a new class and has been recently introduced in JDK 1.2.  HashTable is a legacy class. 
It allows multiple null values and one null key.  It doesn’t allow any null values or key. 

Coding Example

Following is an example of HashMap and HashTable at work so you can understand the distinctions of HashMap vs HashTable. 

Input: 

import java.util.*;

import java.lang.*;

import java.io.*;

public class JavaTester{

   public static void main(String args[]){

      Hashtable ht=new Hashtable();

      ht.put(1,”Uday”);

      ht.put(1,”Ujjwal”);

      ht.put(2,”Sumit”);

      ht.put(3,”Vijay”);

      System.out.println(“————-Hash table————–“);

      Set<Integer> keySet = ht.keySet();

      for (Integer key:keySet) {

         System.out.println(key + ” “+ht.get(key));

      }

      HashMap hm=new HashMap();

      hm.put(0,”Uday”);

      hm.put(4,”Uday”); // you can have duplicate values in a hashmap

      hm.put(1,”Sumit”);

      hm.put(2,”Vijay”);

      System.out.println(“———–Hash map———–“);

      Set<Integer> keySet1 = ht.keySet();

      for (Integer key:keySet) {

         System.out.println(key + ” “+hm.get(key));

      }

   }

}

Output: 

Hash table: 

3 Vijay

2 Sumit

1 Ujjwal

Hash map:

0 Uday

1 Sumit

2 Vijay

4 Uday

When to use HashMap vs HashTable?

The primary factor that determines whether you’ll use HashMap or HashTable is synchronisation. If you need a thread-safe task, then you should use HashTable because all its methods are synchronised. However, it is a legacy class, and you should avoid them.

If you have a multithreaded environment, you should use ConcurrentHashMap as it’s pretty similar to HashTable. It allows you to make the HashMap synchronised properly.

Synchronised operations cause poor performance, so you should avoid them in most cases. Moreover, HashMap is suitable for a non-threaded environment, so you can use it easily. 

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Explore our Popular Software Engineering Courses

Concurrent HashMap vs HashTable

ConcurrentHashMap uses HashTable as its basic data structure. But there still exist a few differences to be noted:

Concurrent HashMap HashTable
While adding or updating the map, Concurrent HashMap only applies locks at the fragment bucket level. The entire collection is locked using a HashTable.
Over a HashTable, it is superior. The entire collection is locked using a HashTable.

Hashmap vs Hashtable: Limitations

When discussing the differences, you must also be familiar with their limitations which can help you choose the correct data structure in Java.

Limitations of HashMap

  • The HashMap performs poorly in case of a chance of collision when two distinct keys produce the same hashCode() value.
  • Sometimes HashMap needs to be resized since the buckets’ original size is full. The elements from the old HashMap are transferred to a new, larger HashMap, which takes O(n) time.

Limitations of Hash table

  • The data to be read is distributed in-memory seemingly at random, which is a problem with HashTables in general.
  • Databases may deteriorate if there are a lot of collisions, which is one of the drawbacks of HashTables. The more data, the greater the chances of collision. Many hash algorithms lack the ability to switch from one data set to another or to the previous data set.

Conclusion

HashMap and HashTable are popular Java codes with similar functions. However, as you can see there are several prominent differences between the two. HashMap is a Java class, whereas HashTable is a data structure. 

If you’re interested in learning more about Java and other programming languages, we recommend checking our Executive PG Programme in Software Development with Specialization in Full Stack Development. 

Read our Popular Articles related to Software Development

What is a hash table?

Hash table is a container data structure that is widely used in computer programming. Hash tables are used to hold key-value pairs, where the key can be any object. As a container, a hash table should support the operations of insert and remove. As a lookup tool, a hash table should support the operation of get. If a hash table is supposed to be a dictionary data structure, it should also support the operation of contains. So, in general, a hash table is a data structure that is widely used to effectively implement the operations of insert, remove, get and contains. The hash table is widely used because of its fast performance.

What is collections framework in Java?

Java Collections Framework is a set of interfaces, classes, and algorithms for the Java Platform. It has been part of the Java Platform since version 1.2. It includes interfaces for containers, lists, queues and so on, but it also includes classes to handle dates and times, a class to handle regular expressions, another to handle internationalization, and yet another to handle searching through files.

What is the relation between a hashtable and hashmap in Java?

A hashtable is a special data structure that associates keys with values. Keys can be any object, but all keys in a given hashtable must be comparable to each other (that is, use the same or compatible interfaces). In Java, a map is a specific kind of hashtable that is implemented using a TreeMap. The keys in a map must implement an equals method, and the map uses this method to determine if two keys are equal or not. This means that only the keys are stored in the map, and their associated value is calculated whenever it is needed.

When would a HashTable be preferable over a HashMap?

HashMap is ideal for non-threading applications if your application does not require any multi-threading tasks.

HashMap is ideal for non-threading applications if your application does not require any multi-threading tasks.

Applications that require several threads should use HashTables.

Want to share this article?

Become a Full Stack Developer

Leave a comment

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

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks