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
Mainclass that inheritsHashTable, consisting ofIntegertype keys andStringtype values to access theHashTable.rehash()method, as it is a protected method. -
In line 4, we made a
mainfunction. -
In line 6, we made an object of the
Mainclass. -
In lines 8 to 12, we inserted values in the
HashTableby using theHashtable.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 theHashTable. -
In line 16, we displayed the size of
HashTableusingHashTable.size()method with a message.
Notice the slight difference in the structure of the
HashTableafter calling therehash()function.