How to Iterate the Vector Elements in the Reverse Order in Java?


The Vector class has been a part of the Java collection system since Java version 1.2. Vectors are sometimes known as Dynamic Arrays because, unlike ordinary arrays, they can expand and contract in size. Ensuring thread-safety, Vectors are synchronized.

While there exists a third approach that involves using Apache Commons to iterate through the vector in reverse, this method necessitates the downloading of additional jar files and packages, which is not widely supported by most systems. Essentially, there are only two primary methods to traverse through vector elements in reverse order.

Methods Used

There are two methods used here −

  • With the help of for loop

  • With the help of ListIterator

Method 1: With the usage of for loop

When it comes to iterating vector elements in the backward direction, one effective approach is to utilize a for loop. By initializing the loop from the index (vector.size()-1) and decrementing until reaching index 0, you can precisely traverse the vector elements from the end to the beginning.

for()

This Java program showcases a practical demonstration of traversing the elements of a vector in reverse order. It begins by creating a vector named "numbers" and populating it with four elements. Utilizing a for loop, it efficiently iterates over the vector in reverse, initiating from the last index, and meticulously prints every element using the println method. As a result, the output accurately represents the elements of the vector displayed in reverse order.

Algorithm

  • Step 1 − Start by importing the necessary Java utility package: import java.util.*;

  • Step 2 − Create a Java class named TLP to encapsulate the code.

  • Step 3 − Add the main method within the TLP class.

  • Step 4 − Within the main method, declare a new Vector object named numbers to store strings: Vector <String> numbers = new Vector<String>();

  • Step 5 − Addition of elements to the vector with the usage of the add method: numbers.add("Ten");, numbers.add("Twenty");, numbers.add("Thirty");, numbers.add("Forty");.

  • Step 6 − Begin a for loop to traverse over the vector elements in reverse order. Initialize the loop variable index with the value of numbers.size() - 1.

  • Step 7 − Set the loop condition to index >= 0.

  • Step 8 − Decrement the index variable by one in each iteration: index--.

  • Step 9 − Within the loop, retrieve and print the element at the current index using the get method of the numbers vector: System.out.println(numbers.get(index));.

  • Step 10 − End the for loop.

  • Step 11 − End the main method.

  • Step 12 − End the TLP class.

Example

import java.util.*;

public class TLP {
   public static void main(String[] args){

      Vector<String> numbers = new Vector<String>();

      // adding elements to vector
      numbers.add("Ten");
      numbers.add("Twenty");
      numbers.add("Thirty");
      numbers.add("Forty");

      for (int index = numbers.size() - 1; index >= 0; index--) {
         System.out.println(numbers.get(index));
      }
   }
}

Output

Forty
Thirty
Twenty
Ten

Method 2

The listIterator() function of the Vector class accepts a starting position as an argument.The ListIterator object that this method provides can be used to loop through the vector's factors starting at the specified point. The vector can be traversed both forward and backward using the ListIterator object.

Syntax

public ListIterator<E> listIterator(int index)

ListIterator supports both forward and backward traversal. We'll utilise the hasPrevious() method of ListIterator to print the backward element to the present index if it is present, because we'll have to traverse backward.

hasPrevious()

The code first creates a vector of strings and adds four elements to it. Then, it creates a list iterator for the vector and iterates over the elements in reverse order, printing each element to the console. The output of the code is the four elements of the vector, printed in reverse order.

Algorithm

  • Step 1 − Import the java.util package.

  • Step 2 − Create a Java class named TLP.

  • Step 3 − Define the main method.

  • Step 4 − Declare a new Vector object named numbers to store strings.

  • Step 5 − Add elements to the vector using the add method.

  • Step 6 − Create a ListIterator object named listIterator and initialize it with the listIterator method of the numbers vector, passing the size() method as an argument.

  • Step 7 − Start a while loop to traverse over the vector elements in reverse order using the hasPrevious method of the listIterator.

  • Step 8 − Within the loop, retrieve and print the previous element using the previous method of the listIterator.

  • Step 9 − End the while loop.

  • Step 10 − End the main method.

  • Step 11 − End the TLP class.

Example

import java.util.*;

public class TLP {
	public static void main(String[] args) {
		// generating a vector of String type
		Vector<String> numbers = new Vector<String>();
		
		// adding elements to vector
		numbers.add("Twenty");
		numbers.add("Thirty");
		numbers.add("Forty");
		numbers.add("Fifty");

		ListIterator<String> listIterator
			= numbers.listIterator(numbers.size());

		// Iterate the ListIterator using the hasPrevious()
		// method

		while (listIterator.hasPrevious()) {
	
			System.out.println(listIterator.previous());
		}
	}
}

Output

Fifty
Forty
Thirty
Twenty

Conclusion

The only two basic ways to iterate through vector elements in reverse order in Java are the two methods discussed in this article. The ListIterator approach is more flexible and adaptable, but the for loop method is more simple and straightforward to use.

Updated on: 18-Oct-2023

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements