- 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 an Iterator in Java
An Iterator can be used to loop through the Vector elements. The method hasNext( ) returns true if there are more elements in the Vector and false otherwise. The method next( ) returns the next element in the Vector and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows −
Example
import java.util.Iterator; import java.util.Vector; public class Demo { public static void main(String args[]) { Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(3); vec.add(9); vec.add(6); vec.add(8); System.out.println("The Vector elements are: "); Iterator i = vec.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
The output of the above program is as follows −
The Vector elements are: 4 1 3 9 6 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 an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows −
Vector vec = new Vector(); vec.add(4); vec.add(1); vec.add(3); vec.add(9); vec.add(6); vec.add(8); System.out.println("The Vector elements are: "); Iterator i = vec.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
- Related Articles
- Loop through an ArrayList using an Iterator in Java
- Loop through a HashMap using an Iterator in Java
- Loop through the Vector elements using a ListIterator in Java
- Iterate through a LinkedList using an Iterator in Java
- Iterate through a Collection using an Iterator in Java
- Enumerate through the Vector elements in Java
- Loop through an array in Java
- How to use Iterator to loop through the Map key set?
- How to loop through an array in Java?
- How to loop through all the elements of an array in C#?
- Searching Elements in Vector Using Index in Java
- Loop through ArrayList in Java
- Retrieving Elements from Collection in Java- Iterator
- How to loop through all the iframes elements of a page using jQuery?
- How to use for each loop through an array in Java?

Advertisements