How to Delete All Values from Java Hashtable


In this example we will show how to remove all values from Hashtable object or clear Hashtable with clear method.

Source Code

package com.beginner.examples;

import java.util.Enumeration;
import java.util.Hashtable;

public class RemoveAllValuesFromHashtable {

	public static void main(String[] args) {
		
		//create Hashtable.
		Hashtable hashtable = new Hashtable();
		
		hashtable.put("1","Alice");
		hashtable.put("2","Bob");
		hashtable.put("3","Jack");
		
		Enumeration enumeration1 = hashtable.elements();
		System.out.println("Before remove all values , hashtable contains :");
		while(enumeration1.hasMoreElements()) {
			System.out.println(enumeration1.nextElement());
		}
		
		/*
		 * To remove all values or clear Hashtable use void clear method() of Hashtable.
		 */
		hashtable.clear();
		Enumeration enumeration2 = hashtable.elements();
		System.out.println("After remove all values , hashtable contains :");
		while(enumeration2.hasMoreElements()) {
			System.out.println(enumeration2.nextElement());
		}
		
	}

}

Output:

Before remove all values , hashtable contains :
Jack
Bob
Alice
After remove all values , hashtable contains :

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments