一个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的中文翻译为:示例 1import 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==============harivamsirohith
在之前的例子中,我们只是显示了员工的姓名,现在我们将显示员工的id和姓名。
示例2import 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中获取元素的几个示例。
以上就是如何使用枚举在java中显示hashtable的元素?的详细内容。