The
Vector
class is a growable array of objects. The elements ofVector
can be accessed using an integer index and the size of aVector
can be increased or decreased. Read more aboutVector
here.
The iterator
method will return an iterator
for the elements of the Vector
object.
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.
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.