. Advertisement .
..3..
. Advertisement .
..4..
Please tell me the way to fix this problem: Exception in thread “main” java.util.nosuchelementexception.
Here is the details:
import java.util.*;
public class sample {
public static void main(String[] args) {
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add(new String("One"));
Iterator itr = arrlist.iterator();
System.out.println(itr.next()); // Iterator has one element
System.out.println(itr.next()); // Iterator is "empty"
}
}
Output:
One
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
at sample.main(sample.java:10)
I look forward to receiving your answers soon. Thanks a lot.
The cause: When trying to access an iterable past its maximum limit, Java throws the NoSuchElementException exception. This means that different accessor methods will throw this exception if the requested element doesn’t exist. The next element in the iteration is returned by Java’s
next()
method, or a NoSuchElementException if there are no more elements in the iteration.Solution:
The exception is to determine whether the iterable’s next position is filled or empty. To determine the later position, utilize the techniques below:
hasNext()
hasMoreElements()
For example: