What is the Vector.iterator method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

The iterator method will return an iterator for the elements of the Vector object.

Syntax

public Iterator<E> iterator()

This method doesn’t take any arguments.

This method returns an iterator for the elements of the Vector. In the returned iterator, the elements are returned from index 0.

Code

import java.util.Vector;
import java.util.Iterator;
class IteratorExample {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
vector.add(4);
Iterator<Integer> itr = vector.iterator();
System.out.println("The elements of the vector is ");
while(itr.hasNext()) {
System.out.print(itr.next() + " , ");
}
}
}

In the code above,

  • In line number 1: We import the Vector class.

  • In line number 4: We create a new Vector object with the name vector.

  • From line numbers 5 to 7: We add four elements(1,2,3,4) to the vector object using the push method.

  • In line number 10: We use the iterator method to get an iterator for the elements of the vector.

  • Then we print the elements of the iterator using the while loop. We use the hasNext method of the iterator object to check if the iterator contains more elements. We use the next method to get the next available element in the iterator.

Free Resources