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

本文概述

  • Java
  • Java
先决条件: Java中的哈希表
我们可以获取Hashtable的键和值作为Enumeration对象。使用keys()和elements()方法, 我们可以分别获取所有键和值作为Enumeration对象。使用类似的枚举方法hasMoreElements()和nextElement()我们可以从中读取与之对应的所有键和值哈希表.
示例1:
Java
//Java program to demonstrate //getting values as an Enumerationimport 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()); } } }

输出如下
GeeksforGeeks

示例2:
Java
//Java program to demonstrate //getting keys as an Enumerationimport 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)); } } }

【如何在Java中使用枚举显示哈希表的元素()】输出如下
Name:RohanArticle:srcminiAge:23Address:India

    推荐阅读