如何在Java中使用Enumeration显示Hashtable的元素?
Hashtable是Java中一个强大的数据结构,允许程序员以键值对的形式存储和组织数据。许多应用程序需要从Hashtable中检索和显示条目。
在Hashtable中,任何非空对象都可以作为键或值。但是,为了成功地从Hashtable中存储和检索项目,用作键的对象必须同时实现equals()方法和hashCode()方法。这些实现确保正确处理键比较和哈希,从而能够有效地管理和检索Hashtable中的数据。
通过使用Hashtable中的keys()和elements()方法,我们可以访问包含键和值的Enumeration对象。
通过使用诸如hasMoreElements()和nextElement()之类的枚举方法,我们可以有效地检索与Hashtable链接的所有键和值,并将它们作为枚举对象获取。这种方法允许无缝遍历和提取Hashtable中的数据。
使用Enumeration的优点
效率:在使用Hashtable等旧版集合类时,枚举效率高且轻量级,因为它不依赖于迭代器。
线程安全:与Iterator不同,Enumeration是一个只读接口,这使得它成为线程安全的,并且是多线程情况下的好选择。
现在让我们来看几个关于如何使用Enumeration从Hashtable获取元素的例子
示例1
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
public class App {
public static void main(String[] args)
{
// we will firstly create a empty hashtable
Hashtable<Integer, String> empInfo
= new Hashtable<Integer, String>();
// now we will insert employees data into the hashtable
//where empId would be acting as key and name will be the value
empInfo.put(87, "Hari");
empInfo.put(84, "Vamsi");
empInfo.put(72, "Rohith");
// now let's create enumeration object
//to get the elements which means employee names
Enumeration<String> empNames = empInfo.elements();
System.out.println("Employee Names");
System.out.println("==============");
// now we will print all the employee names using hasMoreElements() method
while (empNames.hasMoreElements()) {
System.out.println(empNames.nextElement());
}
}
}
输出
Employee Names ============== Hari Vamsi Rohith
在之前的例子中,我们只显示了员工的姓名,现在我们将显示员工的ID和姓名。
示例2
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
public class App {
public static void main(String[] args)
{
// we will firstly create a empty hashtable
Hashtable<Integer, String> empInfo
= new Hashtable<Integer, String>();
// now we will insert employees data into the hashtable
//where empId would be acting as key and name will be the value
empInfo.put(87, "Hari");
empInfo.put(84, "Vamsi");
empInfo.put(72, "Rohith");
// now let's create enumeration objects
// to store the keys
Enumeration<Integer> empIDs = empInfo.keys();
System.out.println("EmpId" + " \t"+ "EmpName");
System.out.println("================");
// now we will print all the employee details
// where key is empId and with the help of get() we will get corresponding
// value which will be empName
while (empIDs.hasMoreElements()) {
int key = empIDs.nextElement();
System.out.println( " "+ key + " \t" + empInfo.get(key));
}
}
}
输出
EmpId EmpName ================ 87 Hari 84 Vamsi 72 Rohith
结论
在本文中,我们讨论了Hashtable和Enumeration的概念及其优点,并且我们还看到了如何使用Enumeration从Hashtable中获取元素以及一些示例。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP