How to use enumeration to display contents of HashTable in Java



Problem Description

How to use enumeration to display contents of HashTable?

Solution

Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the HashTable.

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

public class Main {
   public static void main(String[] args) {
      Hashtable ht = new Hashtable();
      ht.put("1", "One");
      ht.put("2", "Two");
      ht.put("3", "Three");
      Enumeration e = ht.elements();
      
      while(e.hasMoreElements()) {
         System.out.println(e.nextElement());
      }
   }
}

Result

The above code sample will produce the following result.

Three
Two
One
java_collections.htm
Advertisements