Java Utility Library

Java Hashtable - keys() Method



The java.util.Hashtable.keys() method returns an enumeration of the keys in this hashtable.

Syntax

public Enumeration<K> keys()

Here, K is the type of key maintained by the container.


Parameters

No parameter is required.

Return Value

Returns an enumeration of the keys in this hashtable.

Exception

NA

Example:

In the example below, the java.util.Hashtable.keys() method returns an enumeration of the keys in the given hashtable.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hashtable
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

    //populating hashtable
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");
    Htable.put(104, "Jo");

    //printing the content of the hashtable
    System.out.println("Htable contains: " + Htable);

    //creating an Enum of keys of the hashtable
    Enumeration MyEnum = Htable.keys();

    //printing the Enum info
    System.out.println("MyEnum is: " + MyEnum);

    //printing the content of the Enum
    System.out.print("MyEnum contains: ");
    while (MyEnum.hasMoreElements())
      System.out.print(MyEnum.nextElement() + " ");
  }
}

The output of the above code will be:

Htable contains: {104=Jo, 103=Kim, 102=Marry, 101=John}
MyEnum is: java.util.Hashtable$Enumerator@2f2c9b19
MyEnum contains: 104 103 102 101 

❮ Java.util - Hashtable