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.
Example:
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
Syntax
iterator.previousIndex();
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
Syntax
iterator.nextIndex();
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
Example
Java
// Java program to get Previous and// next index using ListIteratorÂ
import java.io.*;import java.util.ArrayList;import java.util.ListIterator;Â
class PreviousAndNextIndex {       public static void main(String[] args)    {        // create empty ArrayList        ArrayList<Integer> arrList            = new ArrayList<Integer>();               // add elements to the ArrayList        arrList.add(5);        arrList.add(10);        arrList.add(15);        arrList.add(20);        arrList.add(25);        arrList.add(30);Â
        // print the initial list        System.out.println("Initial arraylist =>"                           + arrList);Â
        // initializing ListIterator        ListIterator<Integer> iterator            = arrList.listIterator();Â
        // initially iterator is the beginning so        // previousIndex() will return -1        System.out.println("previous index =>"                           + iterator.previousIndex());Â
        // from -1 moving iterator to the 1st index        iterator.next();        iterator.next();Â
        // now iterator is at 1st index        // so nextIterator() will return 2        System.out.println("Next index =>"                           + iterator.nextIndex());    }} |
Output:
Initial arraylist =>[5, 10, 15, 20, 25, 30] previous index =>-1 Next index =>2
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.
