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 Program to Demonstrate Getting Values // as an Enumeration of Hashtable class import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
// Main class // EnumerationOnKeys public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty hashtable
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();
// Inserting key-value pairs into hash table
// using put() method
ht.put( 1 , "Geeks" );
ht.put( 2 , "for" );
ht.put( 3 , "Geeks" );
// Now creating an Enumeration object
// to read elements
Enumeration e = ht.elements();
// Condition holds true till there is
// single key remaining
// Printing elements of hashtable
// using enumeration
while (e.hasMoreElements()) {
// Printing the current element
System.out.println(e.nextElement());
}
}
} |
Geeks for Geeks
Example 2:
// Java Program to Demonstrate Getting Keys // as an Enumeration of Hashtable class // Importing required classes import java.io.*;
import java.util.*;
// Main class class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty hashtable
Hashtable<String, String> ht
= new Hashtable<String, String>();
// Inserting key-value pairs into hash table
// using put() method
ht.put( "Name" , "Rohan" );
ht.put( "Age" , "23" );
ht.put( "Address" , "India" );
ht.put( "Article" , "GeeksforGeeks" );
// Now creating an Enumeration object
// to store keys
Enumeration<String> e = ht.keys();
// Condition holds true till there is
// single key remaining
while (e.hasMoreElements()) {
// Getting key
String key = e.nextElement();
// Printing key and value corresponding to
// that key
System.out.println(key + ":" + ht.get(key));
}
}
} |
Name:Rohan Article:GeeksforGeeks Age:23 Address:India