How HashTable Works Internally in Java?


The Hashtable class is a part of the Java Collection Framework that stores its element in key-value pairs in a hash table. The Key is an object that can be used to fetch and receive value associated with it. There exist a few similarities between a Hashtable and HashMapclass but Hash table is synchronized. Also, its keys must be associated with values, they could not be null. This article aims to explain how Hash table works internally in Java.

Working of Hashtable in Java

We can consider a Hashtable as an array of buckets, where each bucket contains a list of entries. An entry consists of both keys and values. We specify a key and the value thatcan be linked to that key. The key is then hashed to generate a hash code that is furtherused as the index at which the value is stored within the table. The function that helps in getting the location of values from hashcode is called as hash function. It always returns a positive integer value known as hashcode. Multiple objects might get the same integer value after getting evaluated by an in-built method named ‘equals()’. But, similar objects always have same hashcode.

Formula to allocate index

indexNumber = hashNumber % totalBuckets

Here, ‘%’ is the modulo operator that returns remainder

Let’s take an example that shows the use of above formula −

Q. Suppose we got 17 as a hashNumber of an element named XYZ and total number of buckets available is 5. Then, find on which index number it will get stored?

Solution − 17 % 5 = 2 Hence, it will get the index number 2.

Collision in Hashtable

As discussed earlier, multiple objects might get same hashcode which leads to a situation called collision. It occurs when two or more keys have the same hash value and are mapped to the same bucket resulting in slow performance. However, it does not create any functional confusion.

Syntax to declare a Hashtable

Hashtable<TypeOfKey, TypeOfValue> nameOfTable = new Hashtable<>();

Approach

  • First step is to import ‘java.util’ package so that we can use Hashtable class

  • Define an instance of the Hashtable class and append some objects into it using a built-in method named ‘put()’.

  • Now, take a for-each loop and inside it use the ‘keySet()’ method to access all values associated with the keys.

Example 1

The following example illustrates how we can implement a Hashtable in Java.

import java.util.*;
public class Table {
   public static void main(String[] args) {
      Hashtable<String, Integer> workers = new Hashtable<>();
      
      // Adding elements in the workers table
      workers.put("Vaibhav", 4000);
      workers.put("Ansh", 3000);
      workers.put("Vivek", 1500);
      workers.put("Aman", 2000);
      workers.put("Tapas", 2500);
      
      // printing details workers table
      System.out.println("Elements in the given table: ");
      for (String unKey : workers.keySet()) {
         System.out.println("Name: " + unKey + ", Salary: " + workers.get(unKey));
      }
   }
}

Output

Elements in the given table:
Name: Aman, Salary: 2000
Name: Ansh, Salary: 3000
Name: Tapas, Salary: 2500
Name: Vivek, Salary: 1500
Name: Vaibhav, Salary: 4000

Example 2

In the following example, we will retrieve the values of a Hashtable by using the in-built method ‘get()’. This method accepts a key and returns the corresponding value.

import java.util.*;
public class Table {
   public static void main(String[] args) {
      Hashtable<String, Integer> workers = new Hashtable<>();
      
      // Adding elements in the workers table
      workers.put("Vaibhav", 4000);
      workers.put("Ansh", 3000);
      workers.put("Vivek", 1500);
      workers.put("Aman", 2000);
      workers.put("Tapas", 2500);
      
      // printing details workers table one by one
      System.out.println("Value stored at key Ansh: " + workers.get("Ansh"));
      System.out.println("Value stored at key Vivek: " + workers.get("Vivek"));
      System.out.println("Value stored at key Aman: " + workers.get("Aman"));
   }
}

Output

Value stored at key Ansh: 3000
Value stored at key Vivek: 1500
Value stored at key Aman: 2000

Conclusion

We started this article by defining the Hashtable class and in the next section, we explained how it works internally through an example. Later, we discussed the practical implementation of Hashtable through Java example programs.

Updated on: 20-Jul-2023

830 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements