How to Iterate the Vector Elements in the Reverse Order in Java?
Last Updated :
22 Feb, 2021
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
import java.util.*;
class GFG {
public static void main(String[] args)
{
Vector<String> numbers = new Vector<String>();
numbers.add( "One" );
numbers.add( "Two" );
numbers.add( "Three" );
numbers.add( "Four" );
for ( int index = numbers.size() - 1 ; index >= 0 ; index--) {
System.out.println(numbers.get(index));
}
}
}
|
Output
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
import java.util.*;
class GFG {
public static void main(String[] args)
{
Vector<String> numbers = new Vector<String>();
numbers.add( "One" );
numbers.add( "Two" );
numbers.add( "Three" );
numbers.add( "Four" );
ListIterator<String> listIterator
= numbers.listIterator(numbers.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
|
Output
Four
Three
Two
One
Share your thoughts in the comments
Please Login to comment...