Java

How to Fix Java’s Util NoSuchElementException

In Java, the NoSuchElementException is raised when an iterable’s maximum limit is exceeded. This exception is raised by a variety of accessor methods of Enumeration, Iterator, or Tokenizer to signal that the requested element isn’t present. The NoSuchElementException is referred to as an unchecked expectation because it is derived from a RuntimeException. To fix this exception, verify that the underlying object contains more items before implementing the accessor methods that possibly generate the NoSuchElementException. There are some methods to determine whether an object has more elements than it has in the specified interfaces that include these accessor methods.

Example 1:

There, we have different accessor methods that throw this exception if the requested element doesn’t exist. If there are no more elements in the iteration, the next() method in Java gives NoSuchElementException. Otherwise, it returns the next element which is placed in the iteration. We have the following example where we first define the Java class and implement the program inside the main() method of the class. We have the “StrArray” variable declaration where the ArrayList is initialized. We add only one element to the array list which is a string.

Next, we create the “itrArr” variable for the Iterator class to iterate over the elements of the given ArrayList. The “itrArr” variable is then called the “StrArry” along with the iterator() method. After that, we print the next element of the “StrArray” ArrayList which prints the given value of the ArrayList. The next() method is employed to obtain the successive element from an ArrayList. Furthermore, we print the next element from the previous ArrayList which does not exist as we only provided one element to the “StrArray” ArrayList.

import java.util.*;
public class SampleProgram1 {
  public static void main(String[] args) {
ArrayListStrArray = new ArrayList();
StrArray.add(new String("java Example"));
    Iterator itrArr = StrArray.iterator();
System.out.println(itrArr.next());
System.out.println(itrArr.next());
  }
}

The execution of the program raised the NoSuchElementException. It is found as we know that there is no such next element for iteration after the given element is fetched.

Example 2:

The prior example is provided with the source code which raised the NoSuchElementException for the iteration of the next element through the next() method. Now, the next() accessor method of the Iterator class is used in this example to attempt to access a HashMap. But since the HashMap is empty, we receive a NoSuchElementException. First, we have the defined main() method of the Java class where we set the HashSet interface. We declare the “MySet” object of the Set class and assign the HashSet() which is empty. After that, we have the Hashtable object which is “MyTable” where the empty Hashtable() is defined. Then, we employ the iterator with the next() method. The iterator iterates over the set and then gives the next set value. We also get the elements from the Hashtable() through the elements() method and the next element for the table through the nextElement() method. We get a NoSuchElementExeception since both the HashSet and the HashTable are empty.

import java.util.HashSet;  
import java.util.Hashtable;  
import java.util.Set;  
  public class SampleProgram2 {    
    public static void main(String[] args) {  
         Set MySet = new HashSet();  
HashtableMyTable = new Hashtable();  
MySet.iterator().next();              
MyTable.elements().nextElement();                                                
}  
}

There, we get the output that throws the NoSuchElementExecption because we are trying to get the empty elements which are not possible.

Example 3:

Now, we have a solution to avoid the “NoSuchElementException” exception. We need to invoke the iterator which is the hasNext() method. The hasNext() method verifies each time when iterating during the process that an element is present in the set afterward or not. Let’s begin with the hasNext() method program. We first declare the ArrayList class “a” variable where the ArrayList is defined with empty values. We insert the string after the creation of the ArrayList from the add() method. Then, we invoke the “i” iterator object which is called the iterator() method of the ArrayList “a”. The element that traverses with the iterator() is accomplished using the while loop. The while loop has a condition that uses the hasNext() method to verify the existence of the next element from the specified ArrayList. When the hasNext() gives the true indication, the next() method which is deployed in the print statement is executed.

import java.util.*;
public class SampleProgram3 {
  public static void main(String[] args) {    
ArrayList a = new ArrayList();
a.add(new String("Welcome learners"));
    Iterator i = a.iterator();
    while (i.hasNext()) {
System.out.println(i.next());
    }
  }
}

The NoSuchEelementException is not raised from the previous program because the hasNext() checks the elements after and then the next() method provides the element of the ArrayList.

Example 4:

There is another solution for the exception that the StringTokenizer class instance technique hasMoreTokens() examines the tokenizer’s string to determine whether there are any additional tokens. We set the “s” object of String type and assign the string there. After that, we have a “StrToken” object where we call the StringTokenizer class and set the “s” string object and the white space value. Then, we have a while loop iteration where we deploy the hasMoreToken to handle the “NoSuchElementException”. Then, we call the nextToken() method to print the string.

import java.util.StringTokenizer;
public class SampleProgram4{
   public static void main(String args[]) {
      String s = "Java program";
StringTokenizerStrtoken = new StringTokenizer(s, " ");
while(Strtoken.hasMoreTokens()) {
System.out.println(Strtoken.nextToken());
      }
   }
}

There is no exception raised as the hasNextToken() method is performed to handle the exception. The nextToken represents the string values until the end.

Example 5:

The previous() method of the ListIterator returns the collection’s preceding item. A NoSuchElementException is thrown at runtime if the method is used on an empty item or at the item’s starting location. We create the empty ArrayList of a string in the “StringList” variable. After that, we add some strings to the list. The listIterator() is called for the iteration procedure on the ArrayList. Next, we employ the while loop two times in the program. First, the while loop determines the element after through the hasNext() method form which can get the next element by calling the hasNext() method after that. The second while loop uses the hasPrevious() method on the iterator values to get the previous value from the ArrayList. Both of these methods handle the exception by verifying the next and the previous values.

import java.util.ArrayList;
import java.util.ListIterator;
public class SampleProgram5{
   public static void main(String args[]) {
ArrayListStringList = new ArrayList();
StringList.add("java");
StringList.add("ruby");
StringList.add("scala");
ListIteratoritr = StringList.listIterator();
      while(itr.hasNext()) {
itr.next();
      }
      while(itr.hasPrevious()) {
System.out.println(itr.previous());
      }
   }
}

The first gets the next values of the ArrayList from examining through the hasNext() method. Then, we get the previous value of the ArrayList in the output from the hasPrevious() method. The NoSuchElementException is also handled there.

Example 6:

The next simple solution is the hasMoreElements() method of Enumeration which should be used to determine whether this enumeration contains additional elements. Enumeration returns true if it has more elements. Otherwise, it returns false. We generate the empty vectors collection in the “vect” vector object which is added with the numeric value. After that, we specify the “e” Enumeration object to get the elements from its element() method. Then, we deploy the hasMoreElements method() in the while() condition to check whether more elements are provided by the enumeration vectors or not.

import java.util.Enumeration;
import java.util.Vector;
public class SampleProgram6 {
   public static void main(String args[]) {
      Vectorvect = new Vector( );
vect.add(8934);
vect.add(6127);
      Enumeration e = vect.elements();
      while(e.hasMoreElements()) {
System.out.println(e.nextElement());
      }
   }
}

The vector collection of all elements is displayed on the following screen. The hasMoreElement() handles the exception by identifying the further elements.

Conclusion

The NoSuchElementException is resolved by determining if an iterable’s next location is filled or empty. We showed how this error is raised while using the iterable method on the empty collection and the next element from the collection. We have to place the check before iterating it over the elements to get rid of that exception. We provided multiple methods to resolve this exception while executing the program.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.