Reverse Order of All Elements of Java Vector
Vector class Implements a dynamic array means it can shrink and expand its size as required just likely having the same operations like that in the arrays. Don’t confuse it with ArrayList as there is a thin line between vector and ArrayList, where the vector is synchronized rest the insertion order remains the same in both of them. Vector is present in java.util package and implements the list interface
Illustration: Reversing the order of elements in a vector
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Input : [“GEEKS”, “FOR”, “geeks”]
Output: [“geeks”, “FOR”, “GEEKS”]
Method 1: Using for loop to print the element of vector in reverse order.
Before reverse of vector : [1, 2, 3, 4, 5] After reverse of vector : 5 4 3 2 1
Time complexity: O(n) of n time, where n is a number of elements in the vector.
Method 2: Collection.reverse() method as the name suggests is a method of Collection class.
Parameters: Vector object to be reversed
Return value: It returns the reverse of the vector element.
Before Reverse Order, Vector Contains : [GFG, EarlierGreen, NowBlack] After Reverse Order, Vector Contains : [NowBlack, EarlierGreen, GFG]
Method 3: Using listIterator() method
public ListIterator listIterator()
Parameters: This method accepts no input arguments.
Return Value: This method returns a ListIterator object which can be used to traverse the Vector object. This object can be used to traverse the Vector object. It is bidirectional, so both forward and backward traversal is possible, using next() and previous() respectively.
Return Type: A ListIterator
Before: [Geeks, for, Geeks, is, Best] After: Best is Geeks for Geeks