Java Utility Library

Java Vector - listIterator() Method



The java.util.Vector.listIterator() method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified index minus one.

Syntax

public ListIterator<E> listIterator(int index)

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


Parameters

index Specify index of the first element to be returned from the list iterator.

Return Value

Returns a list iterator over the elements in the list (in proper sequence), starting at the specified position in the list.

Exception

Throws IndexOutOfBoundsException, if the index is out of range (index < 0 || index > size()).

Example:

In the example below, the java.util.Vector.listIterator() method returns a list iterator over the elements of the given vector, starting at the specified position.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVec = new Vector<Integer>();

    //populating vector
    for(int i = 1; i <= 5; i++)
      MyVec.add(i*10);

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

    //creating listIterator starting at specified index
    ListIterator itr1 = MyVec.listIterator(3);
    ListIterator itr2 = MyVec.listIterator(4);

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

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

The output of the above code will be:

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

❮ Java.util - Vector