迭代 hastable 键的枚举会引发 NoSuchElementException 错误

2022-08-31 14:15:01

我正在尝试使用枚举从哈希表中循环访问键列表,但是我一直在列表中的最后一个键处获得NoSuchElementException?

Hashtable<String, String> vars = new Hashtable<String, String>();

vars.put("POSTCODE","TU1 3ZU");
vars.put("EMAIL","job.blogs@lumesse.com");
vars.put("DOB","02 Mar 1983");

Enumeration<String> e = vars.keys();

while(e.hasMoreElements()){

System.out.println(e.nextElement());
String param = (String) e.nextElement();
}

控制台输出:

EMAIL
POSTCODE
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
    at java.util.Hashtable$Enumerator.nextElement(Unknown Source)
    at testscripts.webdrivertest.main(webdrivertest.java:47)


答案 1

您在循环中呼叫两次。此调用将枚举指针向前移动。您应该修改代码,如下所示:nextElement()

while (e.hasMoreElements()) {
    String param = e.nextElement();
    System.out.println(param);
}

答案 2
for (String key : Collections.list(e))
    System.out.println(key);