遍历哈希表
HashTable 类提供了一个名为 keys() 的方法,该方法返回一个枚举对象,其中包含哈希表中的所有键。
使用此方法获取键,并使用get()方法检索每个键的值。
Enumeration(接口)的hasMoreElements()方法在枚举对象还有更多元素时返回 true。您可以使用此方法运行循环。
示例
import java.util.Enumeration;
import java.util.Hashtable;
public class Loopthrough {
public static void main(String args[]) {
String str;
Hashtable hashTable = new Hashtable();
hashTable.put("Ram", 94.6);
hashTable.put("Rahim", 92);
hashTable.put("Robert", 85);
hashTable.put("Roja", 93);
hashTable.put("Raja", 75);
Enumeration keys = hashTable.keys();
System.out.println("Contents of the hash table are :");
while(keys.hasMoreElements()) {
str = (String) keys.nextElement();
System.out.println(str + ": " + hashTable.get(str));
}
}
}
输出
Contents of the hash table are : Rahim: 92 Roja: 93 Raja: 75 Ram: 94.6 Robert: 85
广告