Iterator, as we have discussed in earlier topic is for traversing the collection objects and access the elements of that collection. Basically Iterator is for both List Interface and set Interface.
Now we have a special type of Iterator that is only for List Interface which is known as ListIterator. It is even better Iterator for a List containing more utility methods like getting index of elements and adding elements to the base object.
Using ListIterator we can iterate in both the directions, in forward direction as well as backward direction.
1. void add(E e):
This method inserts the specified element into the list.
2. boolean hasNext():
This method returns true if this listIterator has more elements when traversing the list in the forward direction.
3. boolean hasPrevious():
This method returns true if this listIterator has more elements when traversing the list in the backward direction.
4. E next():
This method returns the next element in the list and advances the cursor position one step further.
5. int nextIndex():
This method returns the index of the element that would be returned by a subsequent call to next() method.
6. E previous():
This method returns the previous element in the list and moves the cursor position backwards direction.
7. int previousIndex():
This method returns the index of the element that would be returned by a subsequent call to previous() method.
8. void remove():
This method removes from the list the last element that was returned by next() method or previous() method.
9. void set(E e):
This method replaces the last element returned by next() method or previous() method with the specified element in the argument list
Let us discuss ListIterator with List Implementation with the help of program, following program has been divided into 5 Steps that we will discuss one by one
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class ListIteratorDemo { public static void main(String a[]){ //Step 1: Object of ArrayList is Created of String Type List<String> arrayListObj = new ArrayList<String>(); //Step 2 : Elements are added in the array list arrayListObj.add("This"); arrayListObj.add("is"); arrayListObj.add("Example"); arrayListObj.add("of"); arrayListObj.add("ListIterator"); //Step 3: Obtaining list iterator of type String ListIterator<String> litr =arrayListObj.listIterator(); //Step 4: Traversing in Forward Direction System.out.println("Traversing the list in forward direction:"); while(litr.hasNext()){ System.out.println(litr.next()); } //Step 5: Traversing in Backward Direction System.out.println("\nTraversing the list in backward direction:"); while(litr.hasPrevious()){ System.out.println(litr.previous()); } } }
Output:
Traversing the list in forward direction: This is Example of ListIterator Traversing the list in backward direction: ListIterator of Example is This
Description of Example:
Premium Project Source Code:
Leave a Reply