个性化阅读
专注于IT技术分析

如何在Java中使用枚举显示哈希表的元素?

本文概述

先决条件: Java中的哈希表

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

示例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<Integer, String> ht
             = new Hashtable<Integer, String>();
        
         //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());
         }
     }
}

输出如下

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<String, String> ht
             = new Hashtable<String, String>();
  
         //put key-value pairs into hashtable
         ht.put( "Name" , "Rohan" );
         ht.put( "Age" , "23" );
         ht.put( "Address" , "India" );
         ht.put( "Article" , "srcmini" );
  
         //create enumeration to store keys
         Enumeration<String> 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:srcmini
Age:23
Address:India

赞(0) 打赏
未经允许不得转载:srcmini » 如何在Java中使用枚举显示哈希表的元素?
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏