Java Program to get previous and next index using ListIterator


To get the exact evaluation of the previous and next index, you need use the next() method of the Iterator. This will eventually help you in gaining more understanding about Iterators. Let us first create an ArrayList and add some elements −

ArrayList <Integer> arrList = new ArrayList <Integer> ();
arrList.add(100);
arrList.add(200);
arrList.add(300);
arrList.add(400);
arrList.add(500);
arrList.add(600);
arrList.add(700);
arrList.add(800);
arrList.add(900);
arrList.add(1000);

Now, create a ListIterator −

ListIterator<Integer>iterator = arrList.listIterator();

Get the previous and next index now −

iterator.previousIndex();
iterator.nextIndex();

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<Integer>arrList = new ArrayList<Integer>();
      arrList.add(100);
      arrList.add(200);
      arrList.add(300);
      arrList.add(400);
      arrList.add(500);
      arrList.add(600);
      arrList.add(700);
      arrList.add(800);
      arrList.add(900);
      arrList.add(1000);
      System.out.println("ArrayList...");
      for (Integer i: arrList)
         System.out.println(i);
      ListIterator<Integer>iterator = arrList.listIterator();
      System.out.println("Previous Index =" + iterator.previousIndex());
      System.out.println("Next Index = " + iterator.nextIndex());
      iterator.next();
      System.out.println("Previous Index = " + iterator.previousIndex());
      System.out.println("Next Index =" + iterator.nextIndex());
      iterator.next();
      iterator.next();
      System.out.println("Previous Index = " + iterator.previousIndex());
      System.out.println("Next Index = " + iterator.nextIndex());
   }
}

Output

ArrayList...
100
200
300
400
500
600
700
800
900
1000
Previous Index =-1
Next Index = 0
Previous Index = 0
Next Index =1
Previous Index = 2
Next Index = 3

Updated on: 30-Jul-2019

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements