In this example we will show how to get previous and next index while traversing through elements of ArrayList with ListIterator in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.ListIterator;
public class GetPreviousAndNextIndexListIterator {
public static void main(String[] args) {
//create ArrayList.
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
//Get an object of ListIterator using listIterator() method.
ListIterator listIterator = arrayList.listIterator();
/*
* Use nextIndex and previousIndex methods of ListIterator to get next and
* previous index from the current position in the list.
*/
System.out.println("Previous Index is : " + listIterator.previousIndex());
System.out.println("Next Index is : " + listIterator.nextIndex());
//advance current position by one using next method.
listIterator.next();
System.out.println("Previous Index is : " + listIterator.previousIndex());
System.out.println("Next Index is : " + listIterator.nextIndex());
}
}
Output:
Previous Index is : -1
Next Index is : 0
Previous Index is : 0
Next Index is : 1
References
Imported packages in Java documentation: