is available to only those collections that implement the Java List Interface
has no current element, it's cursor position
always lies between the element that would be returned by a call to
and the element that would be returned by a call to
Advantages of using
iterator you can move only forward, but with
listIterator you can also move reverse while reading the elements.
listIterator you can obtain the index at any point while traversing, which is not possible 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.
listIterator you can add or modify an element at any point while traversing, which is not possible with
public static void main(String arg)
ArrayList ar = new ArrayList();
ListIterator litr = ar.listIterator();
while (litr.hasNext()) // In forward direction
System.out.print(litr.next() + " ");
while (litr.hasPrevious()) // In reverse direction
System.out.print(litr.previous() + " ");
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());
Black Red Blue
Blue Red Black
After adding Orange : Orange
After removing : Red
After setting : Yellow
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 "
LINE C and printed.
THINGS TO TRY
- Add elements "Green", "Purple", "Indigo" to the list using
add method as shown in
- Remove the element
Blue from the list using