Obtain the Previous Index and Next Index in an ArrayList using the ListIterator in Java


The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively in the ListIterator Interface.

The previousIndex() method returns the index of the element that is returned by the previous() method while the nextIndex() method returns the index of the element that is returned by the next() method. Neither of these methods require any parameters.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Amy");
      aList.add("Peter");
      aList.add("Justin");
      aList.add("Emma");
      aList.add("James");
      System.out.println("The ArrayList elements are: "+ aList);
      ListIterator<String> li = aList.listIterator();
      System.out.println("The previous index is: " + li.previousIndex());
      System.out.println("The next index is: " + li.nextIndex());
   }
}

Output

The output of the above program is as follows

The ArrayList elements are: [Amy, Peter, Justin, Emma, James]
The previous index is: -1
The next index is: 0

Now let us understand the above program.

The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed. The previous index and next index in an is obtained using the methods previousIndex() and nextIndex() respectively. A code snippet which demonstrates this is as follows

ArrayList<String> aList = new ArrayList<String>();
aList.add("Amy");
aList.add("Peter");
aList.add("Justin");
aList.add("Emma");
aList.add("James");
System.out.println("The ArrayList elements are: "+ aList);
ListIterator<String> li = aList.listIterator();
System.out.println("The previous index is: " + li.previousIndex());
System.out.println("The next index is: " + li.nextIndex());

Updated on: 29-Jun-2020

785 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements