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

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

一个Hashtable是Java中一种强大的数据结构,允许程序员以键值对的形式存储和组织数据。许多应用程序需要从Hashtable中检索和显示条目。

在Hashtable中,任何非空对象都可以作为键或值。然而,为了成功地存储和检索Hashtable中的项,用作键的对象必须实现equals()方法和hashCode()方法。这些实现确保了键的比较和哈希处理的正确性,从而实现了Hashtable中数据的高效管理和检索。

Through the utilization of the keys() and elements() methods in the Hashtable, we gain access to Enumeration objects containing the keys and values.

通过使用枚举方法,如hasMoreElements()和nextElement(),我们可以有效地检索与Hashtable关联的所有键和值,并将它们作为枚举对象获取。这种方法允许无缝遍历和提取Hashtable中的数据

使用枚举的优点:

  • 效率:当使用旧的集合类(如Hashtable)时,枚举是轻量且高效的,因为它不依赖于迭代器。

  • 线程安全性:枚举是一个只读接口,与迭代器不同,它使其具有线程安全性,并且在多线程环境中是一个很好的选择

现在让我们通过一些例子来说明如何使用Enumeration从Hashtable中获取元素。

Example 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 empInfo = new Hashtable(); // 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 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()); } } } 登录后复制