Java Utility Library

Java Hashtable - rehash() Method



The java.util.Hashtable.rehash() method is used to increase the capacity of this hashtable. This method is called automatically when the number of keys in the hashtable exceeds this hashtable's capacity and load factor.

Syntax

protected void rehash()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.Hashtable.rehash() method is used to increase the capacity of the given hashtable.

import java.util.*;

// extending the class to Hashtable because 
// rehash() is a protected method 
public class MyClass extends Hashtable<Integer, String>{
  public static void main(String[] args) {
    //creating hashtable
    MyClass Htable = new MyClass();

    //populating hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");
    Htable.put(104, "Jo");

    //printing the content of the hashtable
    System.out.println("Htable contains: " + Htable);    

    //rehash() method is used to increase the capacity
    //and re-organizes internally this hashtable
    Htable.rehash();

    //printing size of the hashtable
    System.out.println("size of Htable: " + Htable.size()); 
  }
}

The output of the above code will be:

Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
size of Htable: 4

❮ Java.util - Hashtable