Java Utility Library

Java ArrayList - listIterator() Method



The java.util.ArrayList.listIterator() method returns a list iterator over the elements in the list (in proper sequence). It is bidirectional, so both forward and backward traversal is possible, using next() and previous() respectively.

Syntax

public ListIterator<E> listIterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns a list iterator over the elements in the list (in proper sequence).

Exception

NA.

Example:

In the example below, the java.util.ArrayList.listIterator() method returns a list iterator over the elements of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> MyList = new ArrayList<Integer>();

    //populating the ArrayList
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //print the content of the ArrayList
    System.out.println("MyList contains: " + MyList);

    //creating an listIterator
    ListIterator itr = MyList.listIterator();

    //Forward Traversal
    System.out.println("Forward Traversal: ");
    while(itr.hasNext())
      System.out.println(itr.next()); 

    //Backward Traversal
    System.out.println("Backward Traversal: ");
    while(itr.hasPrevious())
      System.out.println(itr.previous()); 
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40]
Forward Traversal: 
10
20
30
40
Backward Traversal: 
40
30
20
10

❮ Java.util - ArrayList