We can traverse a Vector in forward and Backward direction using ListIterator. Along with this we can perform several other operation using methods of ListIterator API like displaying the indexes of next and previous elements, replacing the element value, remove elements during iteration etc.
Example
Here we have a Vector of Strings and we are iterating it in both the directions using ListIterator.
import java.util.Vector; import java.util.ListIterator; public class VectorListIteratorDemo { public static void main(String[] args) { // Create a Vector Vector<String> vector = new Vector<String>(); //Adding elements to the Vector vector.add("Item1"); vector.add("Item2"); vector.add("Item3"); vector.add("Item4"); vector.add("Item5"); ListIterator litr = vector.listIterator(); System.out.println("Traversing in Forward Direction:"); while(litr.hasNext()) { System.out.println(litr.next()); } System.out.println("\nTraversing in Backward Direction:"); while(litr.hasPrevious()) { System.out.println(litr.previous()); } } }
Output:
Traversing in Forward Direction: Item1 Item2 Item3 Item4 Item5 Traversing in Backward Direction: Item5 Item4 Item3 Item2 Item1
References:
ListIterator javadoc
Vector Javadoc
raghul says
If i give backward direction alone output is empty, but if i give forward direction first and then backward direction am getting the proper output
Chaitanya Singh says
This is because initially the iterator’s current position is at the start of the vector, so when you move backward direction you get an empty output because there is no element before the first element of vector.