Java Utility Library

Java Hashtable - clear() Method



The java.util.Hashtable.clear() method is used to clear the hashtable so that it contains no keys.

Syntax

public void clear()

Parameters

No parameter is required.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.Hashtable.clear() method is used to clear the given hashtable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hashtable
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

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

    //printing hashtable
    System.out.println("Before applying clear() method.");
    System.out.println("Htable contains: " + Htable);

    //clearing all mapping
    Htable.clear();

    //printing hashtable again
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("Htable contains: " + Htable);   
  }
}

The output of the above code will be:

Before applying clear() method.
Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}

After applying clear() method.
Htable contains: {}

❮ Java.util - Hashtable