Menu
Topics Index
...
`

ListIterator Demo - Java Example Program


ListIterator Demo
import java.util.*;

class ListIteratorDemo
{
    public static void main(String arg[])
    {
        ArrayList ar = new ArrayList();
        ar.add("Black");
        ar.add("Red");
        ar.add("Blue");
        ListIterator litr = ar.listIterator();
        while (litr.hasNext()) // In forward direction
        {
            System.out.print(litr.next() + " ");
        }
        System.out.println();
        while (litr.hasPrevious()) // In reverse direction
        {
            System.out.print(litr.previous() + " ");
        }
        System.out.println();
        litr = ar.listIterator(2); // LINE A - Set iterator at specified index
        System.out.println(litr.previousIndex() + " " + litr.nextIndex()); // Indices
        litr.add("Orange"); // LINE B
        System.out.println("After adding Orange : " + litr.previous());
        litr.remove(); // LINE C
        System.out.println("After removing : " + litr.previous());
        litr.set("Yellow"); // LINE D
        System.out.println("After setting : " + litr.next());    
    }
}
OUTPUT

Black Red Blue
Blue Red Black
1 2
After adding Orange : Orange
After removing : Red
After setting : Yellow

DESCRIPTION

In this example, the elements in the list are printed by traversing in either direction. Iterator is set at index 2 and the indices are printed. An element "Orange" is added in LINE A and printed, then the element "Orange" is removed in LINE B and the previous element "Red" is printed and finally the element "Red" is replaced with "Yellow" in LINE C and printed.

THINGS TO TRY
  • Add elements "Green", "Purple", "Indigo" to the list using add method as shown in LINE B.
  • Try for the below code.
    ArrayList ar = new ArrayList();
    ar.add("Black");
    ar.add("Red");
    ar.add("Blue");
    ListIterator litr = ar.listIterator();
    System.out.print(litr.next() + " ");
    System.out.print(litr.next() + " ");
    System.out.print(litr.next() + " ");
    The output for the above code is :
    Black Red Blue when litr.next is invoked for the first time iterator begins at the first element and when it is invoked again it moves to the next element.
  • Remove the element Blue from the list using remove method.

© meritcampus 2019

All Rights Reserved.

Open In App