迭代通过枚举hastable键会抛出NoSuchElementException错误

时间:2011-08-23 11:50:18

标签: java hashtable enumeration key

我正在尝试使用枚举来遍历哈希表中的键列表但是我一直在列表的最后一个键处获得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)

7 个答案:

答案 0 :(得分:95)

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

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

答案 1 :(得分:60)

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

答案 2 :(得分:9)

每次调用e.nextElement()时,都会从迭代器中获取下一个对象。您必须在每次通话之间检查e.hasMoreElement()


示例:

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

答案 3 :(得分:4)

您正在两次调用nextElement。像这样重构:

while(e.hasMoreElements()){


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

答案 4 :(得分:3)

当你只保证你可以在没有例外的情况下调用一次时,你在循环中调用e.nextElement()两次。像这样改写循环:

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

答案 5 :(得分:3)

你在循环中调用nextElement两次。你应该只调用一次,否则它会前进两次:

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

答案 6 :(得分:1)

每次执行e.nextElement()时,您都会跳过一个。所以你在循环的每次迭代中跳过两个元素。

相关问题