📜  Java中如何使用枚举来显示Hashtable的元素?

📅  最后修改于: 2022-05-13 01:54:39.722000             🧑  作者: Mango

Java中如何使用枚举来显示Hashtable的元素?

先决条件: Java中的哈希表

我们可以将 Hashtable 的键和值作为 Enumeration 对象获取。使用 keys() 和 elements() 方法,我们可以分别获取所有键和值作为 Enumeration 对象。使用诸如 hasMoreElements() 和 nextElement() 之类的枚举方法,我们可以从Hashtable中读取对应的所有键和值。

示例 1:

Java
// Java program to demonstrate
// getting values as an Enumeration
  
import java.util.Enumeration;
import java.util.Hashtable;
import java.io.*;
  
public class EnumerationOnKeys {
    public static void main(String[] args)
    {
        // initialize an object of Hashtable
        Hashtable ht
            = new Hashtable();
        
        // insert key-value pairs into hash table
        ht.put(1, "Geeks");
        ht.put(2, "for");
        ht.put(3, "Geeks");
        
        // create an Enumeration object to read elements
        Enumeration e = ht.elements();
  
        // print elements of hashtable using enumeration
        while (e.hasMoreElements()) {
                
              // print the current element
            System.out.println(e.nextElement());
        }
    }
}


Java
// Java program to demonstrate
// getting keys as an Enumeration
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // create hashtable
        Hashtable ht
            = new Hashtable();
  
        // put key-value pairs into hashtable
        ht.put("Name", "Rohan");
        ht.put("Age", "23");
        ht.put("Address", "India");
        ht.put("Article", "GeeksforGeeks");
  
        // create enumeration to store keys
        Enumeration e = ht.keys();
  
        // while keys are present
        while (e.hasMoreElements()) {
  
            // get key
            String key = e.nextElement();
  
            // print key and value corresponding to that key
            System.out.println(key + ":" + ht.get(key));
        }
    }
}


输出
Geeks
for
Geeks

示例 2:

Java

// Java program to demonstrate
// getting keys as an Enumeration
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // create hashtable
        Hashtable ht
            = new Hashtable();
  
        // put key-value pairs into hashtable
        ht.put("Name", "Rohan");
        ht.put("Age", "23");
        ht.put("Address", "India");
        ht.put("Article", "GeeksforGeeks");
  
        // create enumeration to store keys
        Enumeration e = ht.keys();
  
        // while keys are present
        while (e.hasMoreElements()) {
  
            // get key
            String key = e.nextElement();
  
            // print key and value corresponding to that key
            System.out.println(key + ":" + ht.get(key));
        }
    }
}
输出
Name:Rohan
Article:GeeksforGeeks
Age:23
Address:India