Java程序在Hashtable中使用枚举读取元素
Java中的枚举 是预定义的接口之一,其对象仅用于从集合框架变量(如 Stack、Vector、HashTable 等)中向前检索数据,而不是向后检索。
HashTable 是一个类 哈希表类实现了一个 Map,它将键映射到值。它将键/值对存储在哈希表中。在这个数据结构中,我们指定了一个用作键的对象,以及我们想要与该键关联的值。然后对键进行散列,所得散列代码用作将值存储在表中的索引。 HashMap 不提供任何枚举,而 HashTable 提供非快速失败的枚举。哈希表的层次结构如下:
句法:
public class Hashtable extends Dictionary implements Map, Cloneable, Serializable
参数:
- K:插入的键。
- V:分配给键的值。
为了创建哈希表,从Java.util.Hashtable 导入哈希表,其中 K、V 是整数、字符串、浮点数等数据类型。
语法:创建哈希表
Hashtable ht = new Hashtable();
实施:大学生信息
例子
Java
// Java Program to read elements
// using enumeration in hashtable
// Importing enumeration class
import java.util.Enumeration;
// Importing hash table
import java.util.Hashtable;
// Class
public class GFG {
// Main driver method
public static void main(String a[])
{
// Creating hash table
Hashtable hm
= new Hashtable();
// Add key-value pair to Hashtable
// Custom inputs
hm.put("Name", "Bahubali");
hm.put("College", "Amarnath");
hm.put("Department", "Vedics");
// enum
Enumeration keys = hm.keys();
// Condition check whether element(K,V) is present
// using hasMoreElements()
while (keys.hasMoreElements()) {
String key = keys.nextElement();
// Print corresponding key-value pair
System.out.println("Value of " + key
+ " is: " + hm.get(key));
}
System.out.println();
// Creating a new Hashtable
Hashtable hm1
= new Hashtable();
// Adding key-value pair to Hashtable
// Custom inputs
hm1.put("Name", "Ravaan");
hm1.put("College", "SriLanka");
hm1.put("Department", "CS");
// Enum
Enumeration keys1 = hm1.keys();
// Condition check whether element(K,V) is present
// using hasMoreElements()
while (keys1.hasMoreElements()) {
String key = keys1.nextElement();
// Print corresponding key-value pair
System.out.println("Value of " + key
+ " is: " + hm1.get(key));
}
System.out.println();
// Creating a new Hashtable
Hashtable hm2
= new Hashtable();
// Adding key-value pair to Hashtable
// Custom inputs
hm2.put("Name", "Kattappa");
hm2.put("College", "Beardo");
hm2.put("Department", "War");
/// enum
Enumeration keys2 = hm2.keys();
// Condition check whether element(K,V) is present
// using hasMoreElements()
while (keys2.hasMoreElements()) {
String key = keys2.nextElement();
// Print corresponding key-value pair
System.out.println("Value of " + key
+ " is: " + hm2.get(key));
}
}
}
输出
Value of Name is: Bahubali
Value of College is: Amarnath
Value of Department is: Vedics
Value of Name is: Ravaan
Value of College is: SriLanka
Value of Department is: CS
Value of Name is: Kattappa
Value of College is: Beardo
Value of Department is: War