Vector

Vector Iterator example

In this example we shall show you how to obtain a Vector Iterator, in order to iterate through a Vector’s elements. To obtain a Vector Iterator one should perform the following steps:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke iterator() API method of Vector, to get the Iterator.
  • Iterate through the elements of the collection, using hasNext() and next() methods of Iterator,

as described in the code snippet below.
 

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
import java.util.Iterator;
 
public class VectorIteratorExample {
 
  public static void main(String[] args) {
 
    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
    vector.add("element_4");
    vector.add("element_5");
 
    // The Iterator object is obtained using iterator() method
    Iterator it = vector.iterator();
 
    // To iterate through the elements of the collection we can use hasNext() and next() methods of Iterator 
    System.out.println("Vector elements :");
    while(it.hasNext())

System.out.println(it.next());
 
  }
}

Output:

Vector elements :
element_1
element_2
element_3
element_4
element_5

 
This was an example of how to obtain a Vector Iterator in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button