Home » Java Basics » exceptions » java.util.NoSuchElementException – How to solve NoSuchElementException

About Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas
Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

java.util.NoSuchElementException – How to solve NoSuchElementException

In this tutorial we will discuss about NoSuchElementException in Java. This exception is thrown to indicate that there are no more elements in an enumeration.

This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.

Finally, the NoSuchElementException exists since the first version of Java.

 

The Structure of NoSuchElementException

Constructors

  • NoSuchElementException()
  • Creates an instance of the NoSuchElementException class, setting null as its message.

  • NoSuchElementException(String s)
  • Creates an instance of the NoSuchElementException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The NoSuchElementException in Java

The NoSuchElementException can be thrown by the following methods:

All the aforementioned methods try to return the next element of an enumeration and throw that exception, in order to indicate that no more elements exist. A sample example that throws a NoSuchElementException is the following:

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import java.util.StringTokenizer;

public class NoSuchElementExceptionExample {
	public static void main(String[] args) {
		Set sampleSet = new HashSet();
		Hashtable sampleTable = new Hashtable();
		StringTokenizer tokenizer = new StringTokenizer("", ":,");
		
		/* All following statements throw a NoSuchElementException. */
		sampleSet.iterator().next();
		sampleTable.elements().nextElement();
		tokenizer.nextToken();
	}
}

A sample execution is shown below:

Exception in thread "main" java.util.NoSuchElementException
	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1431)
	at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
	at main.java.NoSuchElementExceptionExample.main(NoSuchElementExceptionExample.java:15)

How to deal with the NoSuchElementException

A very common error case is when a Java application tries to iterate over an empty Set. In order to avoid this error, a Java application should call the hasNext first. For example:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MapIterationExample {
	private final static int TOTAL_ELEMENTS = 100;
	
	public static void main(String[] args) {
		Set sampleSet = new HashSet(TOTAL_ELEMENTS);
		
		Iterator ite = sampleSet.iterator();
		while(ite.hasNext())
			System.out.println(ite.next());
	}
}

Accordingly, if a Java application uses enumerations, the hasMoreElements method shall be used:

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

public class EnumerationIterationExample {
	private final static int TOTAL_ELEMENTS = 100;
	
	public static void main(String[] args) {
		Hashtable sampleTable= new Hashtable(TOTAL_ELEMENTS);

		Enumeration tableEnum = sampleTable.elements();
		while(tableEnum.hasMoreElements())
			System.out.println(tableEnum.nextElement());
	}
}

Finally, a proper user of the StringTokenizer is the following:

import java.util.StringTokenizer;

public class StringTokenizerExample {
	public static void main(String[] args) {
		String str = "Hello:from:Java,Code:Geeks";
		StringTokenizer tokenizer = new StringTokenizer(str, ":,");
		
		while(tokenizer.hasMoreTokens())
			System.out.println(tokenizer.nextToken());
	}
}

Download the Eclipse Project

The Eclipse project of this example: NoSuchElementExceptionExample.zip.

 
This was a tutorial about the NoSuchElementException in Java.

(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
priya Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
priya
Guest
priya

import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0) { int n = sc.nextInt(); int[] arr = new int[n]; int count = 0; for(int i = 0 ; i<n;i++) { arr[i] = sc.nextInt(); } for( i = 0 ; i<n-1 ; i++) { for(int j = i+1 ; j<n ; j++) { if(arr[i] < arr[j]) { count = 1; } } if(count == 0) { System.out.print(arr[i] + " "); } } } } } it shows no such element exception