ListIterator : hasNext(), next(), hasPrevious() and previous()

ListIterator is used just like Iterator. For collections that implement List, you can also obtain an iterator by calling listIterator(). A list iterator gives you the ability to access the collection in either the forword or backword direction and lets you modify an element.

The hasPrevious( ) method returns true if there is a previous element. Otherwise, returns false.

The previous( ) method Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

Program

0

 

 

 

Progarm Source

import java.util.ArrayList;
import java.util.ListIterator;

public class Javaapp {

    public static void main(String[] args) {
        
        ArrayList array1 = new ArrayList();
        array1.add(10);
        array1.add(20);
        array1.add(30);
        array1.add(45);
        array1.add(50);
        
        ListIterator itr = array1.listIterator();
        System.out.println("array1 in forward order");
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
        
        System.out.println("array1 in reverse order");
        while(itr.hasPrevious())
        {
            System.out.println(itr.previous());
        }
    }
}

Leave a Comment