Get Previous and Next Index using Java ListIterator
The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively of the ListIterator interface. previousIndex() can also return -1 if it at the beginning of the list.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: list = [2, 3, 6, 8] listiterator is at the beginning find previous index. Output: -1 Input: list = [2, 3, 6, 8] listiterator is at the beginning find next index.
Steps to use previousIndex() and nextIndex():
- Create an empty ArrayList
- Add elements to ArrayList.
- Create a listiterator using listIterator() method.
Listiterator<Integer>iterator = arrList.listIterator();
- Now get the required index using the below commands
Returns: the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list
Returns: the index of the element that would be returned by a subsequent call to next, or list size if the list iterator is at the end of the list
Initial arraylist =>[5, 10, 15, 20, 25, 30] previous index =>-1 Next index =>2