iterating through Enumeration of hastable keys throws NoSuchElementException error

JavaHashtableEnumerationKey

Java Problem Overview


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)

Java Solutions


Solution 1 - Java

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);
}

Solution 2 - Java

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

Solution 3 - Java

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

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

Solution 4 - Java

You are calling nextElement twice. Refactor like this:

while(e.hasMoreElements()){


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

Solution 5 - Java

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:

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

Solution 6 - Java

You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:

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

Solution 7 - Java

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid CunninghamView Question on Stackoverflow
Solution 1 - JavaAlexRView Answer on Stackoverflow
Solution 2 - Javauser3162459View Answer on Stackoverflow
Solution 3 - JavadacweView Answer on Stackoverflow
Solution 4 - JavaHeisenbugView Answer on Stackoverflow
Solution 5 - JavaEdward DaleView Answer on Stackoverflow
Solution 6 - JavaJB NizetView Answer on Stackoverflow
Solution 7 - JavacadrianView Answer on Stackoverflow