Java Utility Library

Java Hashtable - remove() Method



The java.util.Hashtable.remove() method is used to remove the key (and its corresponding value) from this hashtable. This method does nothing if the key is not in the hashtable.

Syntax

public V remove(Object key)

Here, V is the type of value maintained by the container.


Parameters

key Specify key whose mapping is to be removed from the hashtable.

Return Value

Returns the value to which the key had been mapped in this hashtable, or null if the key did not have a mapping.

Exception

Throws NullPointerException, if the key is null.

Example:

In the example below, the java.util.Hashtable.remove() method is used to remove the mapping for the specified key from 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 the hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");
    Htable.put(104, "Jo");

    //printing the hashtable
    System.out.println("Before remove, Htable contains: " + Htable);    

    //remove mapping for 102 key
    Htable.remove(102); 

    //printing the hashtable again
    System.out.println("After remove, Htable contains: " + Htable);  
  }
}

The output of the above code will be:

Before remove, Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
After remove, Htable contains: {104=Jo, 103=Kim, 101=John}

❮ Java.util - Hashtable