Java ListIterator previousIndex() Method Tutorial

In this section, we will learn what the ListIterator previousIndex() method is and how to use it in Java.

What is ListIterator previousIndex() Method in Java?

When traversing a collection object using a ListIterator object in reverse direction, the Java ListIterator previousIndex() method could be used to get the index number of the previous element if we called the previous() method.

ListIterator previousIndex() Method Syntax:

int previousIndex()

ListIterator previousIndex() Method Parameters

The method does not take an argument.

ListIterator previousIndex() Method Return Value

The return value of this method is the index number of the previous element of a collection object.

ListIterator previousIndex() Method Exception:

The method does not throw an exception.

Example: using ListIterator previousIndex() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        ListIterator<String> iterate = list.listIterator();

        while(iterate.hasNext()){
         iterate.next();
        }
        while(iterate.hasPrevious()){
         System.out.println(iterate.previousIndex());
         iterate.previous();
        }
    }
}

Output:

3

2

1

0

Leave a Reply