Java Hashtable keys()方法
我们都知道枚举定义了java类的类型,所以枚举可以有构造函数、方法和实例变量。Java中Hashtable类的java.util.Hashtable.key()方法是用来获取hashtable中存在的键的枚举的。
示例
语法
public Enumeration<K> keys()
Enumeration enu = Hash_table.keys();
Java
返回值: Hashtable的键值的枚举。
例子1 :
// Java Program to Illustrate keys() method
// of Hashtable class
// Importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty Hashtable
// Declaring object of integer and string type
Hashtable<Integer, String> hash_table
= new Hashtable<Integer, String>();
// Inserting elements into the table
// using put() method
// Custom input elements
hash_table.put(10, "Geeks");
hash_table.put(15, "4");
hash_table.put(20, "Geeks");
hash_table.put(25, "Welcomes");
hash_table.put(30, "You");
// Print and display all entered elements in object
System.out.println("The Table is: " + hash_table);
// Creating an empty enumeration to store
Enumeration enu = hash_table.keys();
// Display message
System.out.println("The enumeration of keys are:");
// Condition holds true till there is single element
// remaining using hasMoreElements() method
while (enu.hasMoreElements()) {
// Displaying the Enumeration
System.out.println(enu.nextElement());
}
}
}
Java
输出
The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of keys are:
10
20
30
15
25
Java
例2 :
// Java Program to illustrate keys() method
// of Hashtable class
// Importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty Hashtable
// Declaring object of string and integer type
Hashtable<String, Integer> hash_table
= new Hashtable<String, Integer>();
// Inserting elements into the table
// using put() method
hash_table.put("Geeks", 10);
hash_table.put("4", 15);
hash_table.put("Geeks", 20);
hash_table.put("Welcomes", 25);
hash_table.put("You", 30);
// Displaying the Hashtable
System.out.println("The Table is: " + hash_table);
// Creating an empty enumeration to store
Enumeration enu = hash_table.keys();
// Display message
System.out.println("The enumeration of keys are:");
// Condition holds true till there is single element
// remaining via hasMoreElements() method
while (enu.hasMoreElements()) {
// Displaying the enumeration
System.out.println(enu.nextElement());
}
}
}
Java
输出
The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of keys are:
You
Welcomes
4
Geeks
Java