Java 如何使用枚举显示Hashtable的元素
Hashtable 是Java中的一种强大的数据结构,允许程序员以 键值对 的方式存储和组织数据。许多应用程序需要从Hashtable中检索和显示条目。
在Hashtable中,任何非空对象都可以作为键或值。然而,为了成功地从Hashtable中存储和检索项,用作键的对象必须实现 equals() 方法和 hashCode() 方法。这些实现确保了对键的比较和哈希处理的正确处理,从而实现在Hashtable内部对数据的高效管理和检索。
通过利用Hashtable中的 keys() 和 elements() 方法,我们可以访问包含键和值的 Enumeration 对象。
通过使用 hasMoreElements() 和 nextElement() 等枚举方法,我们可以有效地检索与Hashtable关联的所有键和值,将它们作为枚举对象获取。这种方法允许无缝遍历和提取Hashtable中的数据。
使用枚举的优点:
- 效率 :在使用类似Hashtable的经典集合类时,枚举是轻量级且高效的,因为它不依赖于迭代器。
-
线程安全 :枚举是一个只读接口,不像迭代器那样,它是线程安全的,适用于多线程环境。
现在让我们通过几个示例来演示如何使用枚举从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以及枚举的概念及其优点,并且还看到了如何使用枚举从HashTable中获取元素的几个示例。