How to Use Enumeration to Display Elements of Hashtable in Java?
Last Updated :
18 Nov, 2021
Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
Now here we can get the keys and values of a Hashtable as an Enumeration object using keys() and elements() method. We can obtain all keys and values respectively as an Enumeration object using Enumeration methods like hasMoreElements() and nextElement() we can read all keys and values corresponding to a Hashtable.
Example 1:
Java
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
public class GFG {
public static void main(String[] args)
{
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();
ht.put( 1 , "Geeks" );
ht.put( 2 , "for" );
ht.put( 3 , "Geeks" );
Enumeration e = ht.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
}
}
|
Example 2:
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
Hashtable<String, String> ht
= new Hashtable<String, String>();
ht.put( "Name" , "Rohan" );
ht.put( "Age" , "23" );
ht.put( "Address" , "India" );
ht.put( "Article" , "GeeksforGeeks" );
Enumeration<String> e = ht.keys();
while (e.hasMoreElements()) {
String key = e.nextElement();
System.out.println(key + ":" + ht.get(key));
}
}
}
|
Output
Name:Rohan
Article:GeeksforGeeks
Age:23
Address:India
Share your thoughts in the comments
Please Login to comment...