javacodex.com
Java Examples
Java Examples
memu home questions

ListIterator Example

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its 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().

Source: (ListIteratorExample.java)

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
 
public class ListIteratorExample {
 
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
 
        list.add("John");
        list.add("Ringo");
        list.add("George");
        list.add("Paul");
 
        ListIterator listIterator = list.listIterator();
 
        /*
         * hasNext() returns true if this list iterator has more elements 
         * when traversing the list in the forward direction.
         */
        while (listIterator.hasNext()) {
            /*
             * next() returns the next element in the list 
             * and advances the cursor position.
             */
            System.out.println(listIterator.next());
        }
 
        /*
         * hasPrevious() returns true if this list iterator has more elements 
         * when traversing the list in the reverse direction.
         */
        while (listIterator.hasPrevious()) {
            /*
             * previous() returns the previous element in the list  
             * and moves the cursor position backwards.
             */
            System.out.println(listIterator.previous());
        }
    }
 
}
 

Output:

$ java ListIteratorExample
John
Ringo
George
Paul
Paul
George
Ringo
John

Contact: javacodex@yahoo.com