ListIterator

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. ListIterator is generic interfaces:

interface ListIterator<E>

E specifies the type of objects being iterated.

The methods declared by ListIterator are

void add(E obj)
Inserts obj into the list in front of the element that will be returned by the next call to next( ).
boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
E next( )
Returns the next element.
int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size of the list.
E previous( )
Returns the previous element.
int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns -1.
void remove( )
Removes the current element from the list.
void set(E obj)
Assigns obj to the current element.
 
import java.util.ArrayList;
import java.util.ListIterator;

public class Main {
  public static void main(String args[]) {
    ArrayList<String> al = new ArrayList<String>();
    al.add("C");
    al.add("A");
    al.add("E");
    al.add("B");
    al.add("D");
    al.add("F");
    ListIterator<String> litr = al.listIterator();
    while (litr.hasNext()) {
      String element = litr.next();
      litr.set(element + "+");
    }
    while (litr.hasPrevious()) {
      String element = litr.previous();
      System.out.println(element + " ");
    }
  }
}
  

ListIterator can access the collection in either the forward or backward direction and can modify an element. Otherwise, ListIterator is used just like Iterator.

Home 
  Java Book 
    Collection