What is the HashTable.rehash() method in Java?

The HashTable.rehash() method is present in the HashTable class inside the java.util package.

It is used to increase the capacity of the HashTable. This method is called automatically when the number of keys in the HashTable exceeds this HashTable's capacity and load factor. It also internally reorganizes this HashTable.

Syntax

protected void HashTable.rehash()

Parameters

HashTable.rehash() does not take any parameters.

Return value

HashTable.rehash() does not return anything. This HashTable is modified in-place.

Code

Let’s look at the code snippet below.

import java.util.*;
class Main extends Hashtable<Integer, String>
{
public static void main(String[] args)
{
Main h1= new Main();
h1.put(1, "Let's");
h1.put(5, "see");
h1.put(2, "Hashtable.rehash()");
h1.put(27, "method");
h1.put(9, "in java.");
System.out.println("The Hashtable before rehash() is: " + h1);
h1.rehash();
System.out.println("The Hashtable after rehash() is: " + h1);
System.out.println("Size of Hashtable: " + h1.size());
}
}

Explanation

  • In line 1, we imported the required package.

  • In line 2, we made a Main class that inherits HashTable, consisting of Integer type keys and String type values to access the HashTable.rehash() method, as it is a protected method.

  • In line 4, we made a main function.

  • In line 6, we made an object of the Main class.

  • In lines 8 to 12, we inserted values in the HashTable by using the Hashtable.put() method.

  • In line 14, we displayed the original HashTable.

  • In line 15, we used HashTable.rehash() to increase the capacity if the number of keys exceeds in the HashTable.

  • In line 16, we displayed the size of HashTable using HashTable.size() method with a message.

Notice the slight difference in the structure of the HashTable after calling the rehash() function.

Free Resources