What is the Vector.iterator method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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
Vectorclass. -
In line number 4: We create a new
Vectorobject with the namevector. -
From line numbers 5 to 7: We add four elements(
1,2,3,4) to thevectorobject using thepushmethod. -
In line number 10: We use the
iteratormethod to get aniteratorfor the elements of thevector. -
Then we print the elements of the iterator using the
whileloop. We use thehasNextmethod of the iterator object to check if the iterator contains more elements. We use thenextmethod to get the next available element in the iterator.