Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through Enumeration of hastable keys throws NoSuchElementException error

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)  
like image 350
David Cunningham Avatar asked Aug 23 '11 11:08

David Cunningham


People also ask

How do I fix Java Util NoSuchElementException?

Solution. The solution to this​ exception is to check whether the next position of an iterable is filled or empty. You should only move to this position if the check returns that the position is not empty.

What is a NoSuchElementException in Java?

NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

What is enumeration and iterator in Java?

In Iterator, we can read and remove element while traversing element in the collections. Using Enumeration, we can only read element during traversing element in the collections. 2. Access. It can be used with any class of the collection framework.


2 Answers

You call nextElement() twice in your loop. This call moves the enumeration pointer forward. You should modify your code like the following:

while (e.hasMoreElements()) {     String param = e.nextElement();     System.out.println(param); } 
like image 83
AlexR Avatar answered Nov 01 '22 00:11

AlexR


for (String key : Collections.list(e))     System.out.println(key); 
like image 20
user3162459 Avatar answered Oct 31 '22 23:10

user3162459