- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Loop through the Vector elements using a ListIterator in Java
A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in a Vector. The method hasNext( ) in ListIterator returns true if there are more elements in the Vector while traversing in the forward direction and false otherwise. The method next( ) returns the next element in the Vector and advances the cursor position.
A program that demonstrates this is given as follows −
Example
import java.util.ListIterator; import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(); vec.add(3); vec.add(4); vec.add(6); vec.add(2); vec.add(9); vec.add(8); System.out.println("The Vector elements are: "); ListIterator i = vec.listIterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
The output of the above program is as follows −
The Vector elements are: 3 4 6 2 9 8
Now let us understand the above program.
The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using the listIterator() method which makes use of the ListIterator interface. A code snippet which demonstrates this is as follows −
Vector vec = new Vector(); vec.add(3); vec.add(4); vec.add(6); vec.add(2); vec.add(9); vec.add(8); System.out.println("The Vector elements are: "); ListIterator i = vec.listIterator(); while (i.hasNext()) { System.out.println(i.next()); }