How to Iterate the Vector Elements in the Reverse Order in Java?
The Vector class is found in java.util package and it implements List interface. The Vector class is included in the java collection framework from Java version 1.2. Unlike arrays, vectors can grow and shrink their size, and thus they are also called the Dynamic Array. Vectors are synchronized, ie they are thread-safe.
There are basically two methods to iterate vector elements in reverse order, though there is another method using Apache Commons for iterating the vector backward in the backward direction but to use it, we just have to download some jar files and packages and also, the majority of the system does not support apache-commons.
We will be using two methods:
- Using For Loop
- Using ListIterator
Method 1: Using For Loop
To Iterate vector elements in backward direction using for loop, we can traverse vector from backward direction by running a loop from the index (vector. size()-1) to index 0.
Java
// Java Program to traverse the vector elements in backward // direction import java.util.*; class GFG { public static void main(String[] args) { // creating a vector of String type Vector<String> numbers = new Vector<String>(); // adding elements to vector numbers.add( "One" ); numbers.add( "Two" ); numbers.add( "Three" ); numbers.add( "Four" ); // Iterating from index equal to numbers.size()-1to // 0 and decrement index by 1 using the for loop for ( int index = numbers.size() - 1 ; index >= 0 ; index--) { System.out.println(numbers.get(index)); } } } |
Four Three Two One
Method 2: Using ListIterator
The Vector class has ListIterator method, which is used to iterate over the vectors. The ListIterator method takes the starting index from where traversal has to begin and returns the ListIterator.
- ListIterator has methods to traversal forward as well as backward. Since we have to traverse backward, so we will pass starting index as equal to the size of the array, and then we will use the hasPrevious() method of ListIterator, in which we will print the backward element to the current index if exists.
Java
// Java Program to traverse the vector elements in backward // direction using ListIterator import java.util.*; class GFG { public static void main(String[] args) { // creating a vector of String type Vector<String> numbers = new Vector<String>(); // adding elements to vector numbers.add( "One" ); numbers.add( "Two" ); numbers.add( "Three" ); numbers.add( "Four" ); // listIterator method will return the list of // String of type ListIterator. ListIterator<String> listIterator = numbers.listIterator(numbers.size()); // Iterate the ListIterator using the hasPrevious() // method while (listIterator.hasPrevious()) { // if element exist at previous index,then print // that element System.out.println(listIterator.previous()); } } } |
Four Three Two One
Please Login to comment...