The HashTable.remove()
method is present in the HashTable
class inside the java.util
package. The HashTable.remove()
method is used to remove the key and its mapped value from the HashTable
.
Key
: The key that is to be removed with its mapped value from the HashTable
.HashTable.keys()
returns:
Value
: The value that was mapped with the key to be removed.Null
: If there was no mapping available with that key passed as an argument.Let’s have a look at the code below.
import java.util.*; class Main { public static void main(String[] args) { Hashtable<Integer, String> h1 = new Hashtable<Integer, String>(); h1.put(1, "Let's"); h1.put(5, "see"); h1.put(2, "Hashtable.remove()"); h1.put(27, "method"); h1.put(9, "in java."); System.out.println("The Hashtable is: " + h1); String removed_value = (String)h1.remove(2); System.out.println("Removed value is: " + removed_value); String rv = (String)h1.remove(24); System.out.println("Removed value is: " + rv); System.out.println("New table is: " + h1); } }
In line 1, we import the required package.
In line 2, we make a Main
class.
In line 4, we make a main
function.
In line 6, we declare a Hashtable
consisting of Integer
type keys and String
type values.
From lines 8 to 12, we insert values in the Hashtable by using the Hashtable.put()
method.
In line 15, we display the original Hashtable
.
In line 17, we use the HashTable.remove()
method to remove a specified key from the HashTable
and display the value mapped with the removed key in line 18.
In line 19, we use the HashTable.remove()
method to remove a new key from the HashTable
whose mapping is not defined in the HashTable
and display the value mapped with the removed key in line 20.
In line 22, we display the new HashTable
, which has the removed key-value pairs after the usage of the HashTable.remove()
method.
In this way, we can use the HashTable.remove()
method to remove the key and its mapped value from the HashTable
.
RELATED TAGS
CONTRIBUTOR
View all Courses