ListIterator
is available to only those collections that implement the
Java List Interface . A
listIterator
has no current element, it's
cursor position always lies between the element that would be returned by a call to
previous()
and the element that would be returned by a call to
next()
.
Advantages of using listIterator
over iterator
:
-
With
iterator
you can move only forward, but with listIterator
you can also move reverse while reading the elements.
-
With
listIterator
you can obtain the index at any point while traversing, which is not possible with iterator
.
-
With
iterator
you can only check whether the next element is available or not, but with listIterator
you can check the previous and next elements.
-
With
listIterator
you can add or modify an element at any point while traversing, which is not possible with iterator
.
ListIterator Methods:
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());
}
}
OUTPUTBlack Red Blue
Blue Red Black
1 2
After adding Orange : Orange
After removing : Red
After setting : Yellow
DESCRIPTIONIn 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
.
- Remove the element
Blue
from the list using remove
method.