Skip to content
Related Articles

Related Articles

Get Previous and Next Index using Java ListIterator

Improve Article
Save Article
  • Last Updated : 17 Dec, 2020
Improve Article
Save Article

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!