Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the Hashtable.clear() function in Java?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

In this shot, we discuss how to use the Hashtable.clear() method in Java.

The Hashtable.clear() method is present in the Hashtable class inside the java.util package. It is used to remove all the keys from the specified Hashtable.

Parameter

Hashtable.clear() method does not take any parameters.

Return

This method does not return anything.

Example

Let’s understand this with the help of an example.

Suppose we have a HashTable = {1 = Let's, 5 = see, 2 = Hashtable.clear(), 27 = method}

When we use HashTable.clear() method on this HashTable, it removes all keys from the HashTable, making the HashTable blank.

So, the result of the HashTable.clear() method is [ ].

Code

Let’s look at the code snippet below to understand this better.

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.clear()");
h1.put(27, "method");
h1.put(9, "in java.");
System.out.println("The Hashtable is: " + h1);
h1.clear();
System.out.println("The Hashtable after using Hashtable.clear() method is: " + h1);
}
}
Using Hashtable.clear() function in Java

Explanation

  • 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.
  • In lines 9 to 13, we insert values in the Hashtable by using the Hashtable.put() method.
  • In line 16, we display the original Hashtable.
  • In line 17, we remove all the keys from the Hashtable using Hashtable.clear() method.
  • In line 18, we display the Hashtable with a message.

In this way, we can use the Hashtable.clear() function to remove all the keys from the Hashtable.

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring