In this section, we will learn what the ListIterator next() method is and how to use it in Java.
What is ListIterator next() Method in Java?
The Java ListIterator next() method is used to get the next element in a collection via a ListIterator object.
Note: if you call this method and there’s no element in the target collection left to be returned, you’ll get an exception in return. So for this reason, it is better to check and see if there’s an element in the target collection using the hasNext() method and then, if there was, call the next() method then.
ListIterator next() Method Syntax:
E next()
ListIterator next() Method Parameters
The method does not take an argument.
ListIterator next() Method Return Value
The return value of this method is the next element in the target collection object.
ListIterator next() Method Exception:
This method might throw one exception:
NoSuchElementException: We get this exception if we attempt to get the next element in a collection when there’s no element left to be returned.
Example: using ListIterator next() Method in Java
import java.util.List; import java.util.ArrayList; import java.util.ListIterator; public class Main { public static void main(String[] args){ List<String> list = new ArrayList<>(); list.add("Omid"); list.add("Jack"); list.add("Ellen"); list.add("John"); ListIterator<String> iterate = list.listIterator(); while(iterate.hasNext()){ System.out.println(iterate.next()); } } }
Output:
Omid Jack Ellen John
How Does ListIterator next() Method Work in Java?
In this example, as you can see, we first checked the collection using the hasNext() method to make sure there’s actually an element to be returned and then called the next() method.