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.
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.
Four Three Two One
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.