Java Vector listIterator() Method Example

The iterator() method of java.util.Vector class will returns iterator over the elements in the list in proper sequence sameway listIterator() method will return a list iterator over the elements in the list. Using the iterator() method we will be able to traverse in the forward direction only but listIterator() method allows you to traverse in both forward and reverse direction.

Signature

public ListIterator<E> listIterator() 

This method returns list iterator over the elements in the list in proper sequence. Returned iterator will be a fail-fast iterator

Example

The following example shows the usage of java.util.Vector.listIterator() method.

import java.util.ListIterator;
import java.util.Vector;

public class ListIteratorMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        vector1.add("Element5");
        
        //Get ListIterator object using listIterator() method
        ListIterator li = vector1.listIterator();
        
        System.out.println("***Forward Iteration***");
        //Lets iterate in the forward direction
        while(li.hasNext())
        {
            System.out.println(li.next());
        }
        
        System.out.println("***Reverse Iteration***");
        //Lets iterate in the reverse direction
        while(li.hasPrevious())
        {
            System.out.println(li.previous());
        }
    }
}

Output

***Forward Iteration***
Element1
Element2
Element3
Element4
Element5
***Reverse Iteration***
Element5
Element4
Element3
Element2
Element1

Leave a Reply

Your email address will not be published. Required fields are marked *