How to reverse all elements in vector and ArrayList?

You may have following questions like :
How to reverse the order of elements in java Vector ?
How to reverse the order of elements in java ArrayList?

You can easily reverse the order of elements in Vector and ArrayList using Collections class.
java.util.Collections class contain lot of static methods which normally operates on collections or return collections. To reverse the order of elements there is a static method in the collections class i.e reverse which will reverse the order of elements.

Lets see at how to do this :


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

public class ReverseOrder {

public static void main(String[] args) {



//creating an ArrayList object

ArrayList reverseDemoList = new ArrayList();



//Adding elements to Arraylist

reverseDemoList.add("1");
reverseDemoList.add("2");
reverseDemoList.add("3");
reverseDemoList.add("4");


System.out.println("ARRAYLIST REVERSE DEMO ");

System.out.println("Before Reverse Order : " + reverseDemoList);


Collections.reverse(reverseDemoList);


System.out.println("After Reverse Order : " + reverseDemoList);

//creating a Vector object

Vector reverseVector = new Vector();

//Adding elements to Vector

reverseVector.add("V");
reverseVector.add("E");
reverseVector.add("C");
reverseVector.add("T");
reverseVector.add("O");
reverseVector.add("R");

System.out.println("VECTOR REVERSE DEMO ");
System.out.println("Before Reverse Order " + reverseVector);

Collections.reverse(reverseVector);

System.out.println("After Reverse Order : " + reverseVector);

}
}

Output :

ARRAYLIST REVERSE DEMO
Before Reverse Order : [1, 2, 3, 4]
After Reverse Order : [4, 3, 2, 1]
VECTOR REVERSE DEMO
Before Reverse Order [V, E, C, T, O, R]
After Reverse Order : [R, O, T, C, E, V]
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment