Java Hashtable clear() Method Example

The clear() method of java.util.Hashtable class will clear this hashtable so that it contains no keys.

Signature

public void clear()

This method clears this hashtable so that it contains no keys.

Example

The following example shows the usage of java.util.Hashtable.clear() method.

import java.util.Hashtable;
import java.util.Map;

public class ClearMethodHashtableExample 
{
    public static void main(String args[])
    {
        // create an empty Hashtable
        Hashtable<Integer,String>  hashtable1 = new Hashtable<Integer,String>();
        
        // use put() method to put elements to the Hashtable
        hashtable1.put(1,"Element1");
        hashtable1.put(2,"Element2");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        hashtable1.put(3,"Element3");
        
        //printing the elements of the hashtable
        System.out.println("**Elements of the hashtable before clear**");
        System.out.println("**Size of hashtable1 is : \""+hashtable1.size()+"\"**");
        for(Map.Entry<Integer,String> mapEntry : hashtable1.entrySet())
        {
            System.out.println("Key : "+mapEntry.getKey()+" Value : "+mapEntry.getValue());
        }
        
        //Clear the elements of the hashtable
        hashtable1.clear();
        
        //printing the elements of the hashtable
        System.out.println("**Elements of the hashtable after clear**");
        System.out.println("**Size of hashtable1 is : \""+hashtable1.size()+"\"**");
        for(Map.Entry<Integer,String> mapEntry : hashtable1.entrySet())
        {
            System.out.println("Key : "+mapEntry.getKey()+" Value : "+mapEntry.getValue());
        }
    }
}

Output

**Elements of the hashtable before clear**
**Size of hashtable1 is : "5"**
Key : 5 Value : Element5
Key : 4 Value : Element4
Key : 3 Value : Element3
Key : 2 Value : Element2
Key : 1 Value : Element1
**Elements of the hashtable after clear**
**Size of hashtable1 is : "0"**

Leave a Reply

Your email address will not be published. Required fields are marked *