java.util.NoSuchElementException in HashTable while Iterating using Enumeration in java


In this Example we are going to understand the exceptions with HashTable while iterating using Enumeration.

Error Message :
Exception in thread "main" java.util.NoSuchElementException
       at java.base/java.util.Collections$EmptyEnumeration.nextElement(Collections.java:4289)
       at HashTableOperations.main(HashTableOperations.java:12)


Error Description :

import java.util.Enumeration;
import java.util.Hashtable;

public class HashTableOperations {

       public static void main(String[] args) {
              Hashtable<String, String> ht = new Hashtable<String, String>();
              Enumeration<String> en = ht.elements();
              System.out.println(en.nextElement());
             
       }

}
In the above example ,the red background color line is giving the exception.
We have defined the HashTable but we did not add any element to the HashTable .
When we are iterating the HashTable using Enumeration then there it will call en.nextElement() method which will give the next element but here the HashTable is empty.So we will get the NoSuchElement Exception.

Solution:

Before going to get nextElement first we need to check whether the HashTable having any elements ae there or not. The hasMoreElements() method   of Enumeration will check the elements availability. If no elements found then it ll return false value.
So we wont get any excepions.

import java.util.Enumeration;
import java.util.Hashtable;

public class HashTableOperations {

       public static void main(String[] args) {
              Hashtable<String, String> ht = new Hashtable<String, String>();
              Enumeration<String> en = ht.elements();
              while(en.hasMoreElements()) {
              System.out.println(en.nextElement());
              }
System.out.println(ht.size());
       }

}
                         
Output:
0
Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar