Java ListIterator previous() Method Tutorial

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

What is ListIterator previous() Method in Java?

When traversing a collection object using a ListIterator object in a reverse direction, we can use the `previous()` method to get the previous element in the target collection object.

Note: if you try to get the previous element in a collection but there wasn’t any element left, you’ll get an exception in return! So it’s best to use this method with the hasPrevious() method to first check and see if there’s any and then run the previous() method.

ListIterator previous() Method Syntax:

E previous()

ListIterator previous() Method Parameters

The method does not take an argument.

ListIterator previous() Method Return Value

The return value of this method is the previous element in the target collection object.

ListIterator previous() Method Exception:

This method might throw one exception and that is:

NoSuchElementException: We get this exception if we attempt to get the previous element in a collection when there’s no element left to be returned.

Example: using ListIterator previous() 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.previous());
        }
    }
}

Output:

John

Ellen

Jack

Omid

 

Leave a Reply