迭代 hastable 键的枚举会引发 NoSuchElementException 错误
我正在尝试使用枚举迭代哈希表中的键列表,但是我在列表中的最后一个键处不断收到 NoSuchElementException ?
Hashtable<String, String> vars = new Hashtable<String, String>();
vars.put("POSTCODE","TU1 3ZU");
vars.put("EMAIL","[email protected]");
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)
I am trying to iterate through a list of keys from a hash table using enumeration however I keep getting a NoSuchElementException at the last key in list?
Hashtable<String, String> vars = new Hashtable<String, String>();
vars.put("POSTCODE","TU1 3ZU");
vars.put("EMAIL","[email protected]");
vars.put("DOB","02 Mar 1983");
Enumeration<String> e = vars.keys();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
String param = (String) e.nextElement();
}
Console output:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您在循环中调用
nextElement()
两次。该调用将枚举指针向前移动。您应该像下面这样修改您的代码:
You call
nextElement()
twice in your loop. This call moves the enumeration pointer forward.You should modify your code like the following:
每次调用
e.nextElement()
时,您都会从迭代器中获取下一个对象。您必须在每次调用之间检查e.hasMoreElement()
。例子:
Every time you call
e.nextElement()
you take the next object from the iterator. You have to checke.hasMoreElement()
between each call.Example:
您正在调用 nextElement 两次。像这样重构:
You are calling nextElement twice. Refactor like this:
当您只保证可以调用一次而不会出现异常时,您会在循环内调用
e.nextElement()
两次。像这样重写循环:You're calling
e.nextElement()
twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:您在循环中调用 nextElement 两次。你应该只调用它一次,否则它会前进两次:
You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:
每次执行
e.nextElement()
时,您都会跳过一个。因此,您在循环的每次迭代中跳过两个元素。Each time you do
e.nextElement()
you skip one. So you skip two elements in each iteration of your loop.