What is the cause of NoSuchElementException and how can we fix it in java?

Java 8Object Oriented ProgrammingProgramming

What is the cause of NoSuchElementException and how can we fix it in java?

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Each exception is represented by its respective class.

Cause for NosuchElementException

This is a Runtime exception i.e. it occurs at the execution time.

While accessing the contents of a collection, array or other objects using the accessor methods of an Enumeration, Iterator or, tokenizer, such as next() or nextElement(), if you try to get the elements from an empty object, or if you try to get the next element after reaching the end of the object (collection, array, or other) a NoSuchElementException is generated.

For example,

  • If you call the nextElement() method of the Enumeration class on an empty enumeration object or, if the current position is at the end of the Enumeration, a NosuchElementException is generated at run time.
  • If you nextElement() and nextToken() methods of the StringTokenizer class on an empty StringTokenizer object or, if the current position is at the end of the StringTokenizer, a NosuchElementException is generated at run time.
  • If the next() methods of the Iterator or ListIterator classes, invoked on an empty Iterator/ListIterator or, if the current position is at the end, the Iterator/listIterator NosuchElementException is generated at run time.
  • Similarly if the previous() method of the ListIterator class is invoked on an empty ListIterator object, or if the current position is the start of the ListIterator a NosuchElementException is generated at run time.

Example

import java.util.StringTokenizer;
public class StringTokenizerExample{
   public static void main(String args[]) {
      String str = "Hello how are you";
      //Instantiating the StringTokenizer class
      StringTokenizer tokenizer = new StringTokenizer(str, " ");
      //Printing all the tokens
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      System.out.println(tokenizer.nextToken());
      //Getting the next token after reaching the end
      tokenizer.nextToken();
      tokenizer.nextElement();
   }
}

Runtime error

Hello
how
are
you
Exception in thread "main" java.util.NoSuchElementException
   at java.util.StringTokenizer.nextToken(Unknown Source)
   at MyPackage.StringTokenizerExample.main(StringTokenizerExample.java:16)

Handling/Fixing NosuchElementException

Almost all the classes whose accessor method causes NoSuchElementException contains their respective methods to verify whether the object (collection, tokenizer etc.) contains more elements.

For example −

  • The Enumeration class contains a method named hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false).
  • The StringTokenizer class contains methods named hasMoreTokens() and hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false).
  • The Iterator class contains hasNext() method this also returns true if the current iterator contains more elements next to the current position (else it returns false).
  • The ListIterator class contains hasPrevious() method this also returns true if the current iterator contains more elements previously to the current position (else it returns false).

In the while loop verify whether the respective object contains more elements using these methods, print/access elements only, if the condition is true. This prevents the access of elements using accessor methods when there are no elements in the object or, if it reaches the end.

hasMoreElements() method of the Enumeration class

import java.util.Enumeration;
import java.util.Vector;
public class EnumExample {
   public static void main(String args[]) {
      //instantiating a Vector
      Vector<Integer> vec = new Vector<Integer>( );
      //Populating the vector
      vec.add(1254);
      vec.add(4587);
      //Retrieving the elements using the Enumeration
      Enumeration<Integer> en = vec.elements();
      while(en.hasMoreElements()) {
         System.out.println(en.nextElement());
      }
   }
}

Output

1254
4587

nextMoreTokens() method of the StringTokenizer class

import java.util.StringTokenizer;
public class StringTokenizerExample{
   public static void main(String args[]) {
      String str = "Hello how are you";
      //Instantiating the StringTokenizer class
      StringTokenizer tokenizer = new StringTokenizer(str, " ");
      //Printing all the tokens
      while(tokenizer.hasMoreTokens()) {
         System.out.println(tokenizer.nextToken());
      }
   }
}

Output

Hello
how
are
you

hasNext() method of the Iterator class

import java.util.ArrayList;
import java.util.Iterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      Iterator it = list.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}

Output

apples
mangoes
oranges

hasPrevious() method of the ListIterator class

import java.util.ArrayList;
import java.util.ListIterator;
public class NextElementExample{
   public static void main(String args[]) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      //populating the ArrayList
      list.add("apples");
      list.add("mangoes");
      list.add("oranges");
      //Getting the Iterator object of the ArrayList
      ListIterator<String> it = list.listIterator();
      while(it.hasNext()) {
         it.next();
      }
      while(it.hasPrevious()) {
         System.out.println(it.previous());
      }
   }
}

Output

oranges
mangoes
apples
raja
Published on 06-Aug-2019 09:00:01
Advertisements