In this section, we will learn what the ListIterator nextIndenx() method is and how to use it in Java.
What is ListIterator nextIndex() Method in Java?
The Java ListIterator nextIndex() method is used to return the index of the next element of a collection object if we call the next() method.
Note: using this method won’t push the cursor of the ListIterator object! It just gives you a hint of what the index number for the next element is.
ListIterator nextIndex() Method Syntax:
int nextIndex()
ListIterator nextIndex() Method Parameters
The method does not take an argument.
ListIterator nextIndex() Method Return Value
The return value of this method is the index number of the next element that, if we call the next() method, it will return.
ListIterator nextIndex() Method Exception:
The method does not throw an exception.
Example: using ListIterator nextIndex() 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.nextIndex()); iterate.next(); } } }
Output:
0 1 2 3