How to Reverse Vector Elements in Java


In this example, let us see how to reverse the order of all elements of Vector with reverse method of Collections class in Java.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.Vector;

public class ReverseVectorExample {
	
	public static void main(String[] args)
	{
		Vector vector = new Vector();
		
		vector.add("1");
		vector.add("2");
		vector.add("3");
		vector.add("4");
		
		//
		System.out.println("Vector:"+vector);
		
		//Use the reverse() method in the Collections utility class to do the reverse
		Collections.reverse(vector);
		
		System.out.println("After the reverse:"+vector);
		
	}

}

Output:

Vector:[1, 2, 3, 4]
After the reverse:[4, 3, 2, 1]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments