Write a Java program to iterate Vector collection using the iterator() method


The code you provided demonstrates how to iterate over the elements of a Vector using an Iterator in Java. Here's a breakdown of what the code does:

  • A Vector<String> object named vec_list is created.
  • Elements "Red", "Green", "Blue", "Yellow", and "Orange" are added to vec_list using the add method.
  • An Iterator object named itr is created by calling the iterator method on vec_list.
  • The message "Vector Elements are : " is printed using System.out.println.
  • The while loop is used to iterate over the elements of vec_list using the Iterator. The loop continues as long as itr has more elements (hasNext method returns true).
  • Inside the loop, the next method is used to retrieve the next element from itr, and it is printed using System.out.println.

Source Code

import java.util.*;
public class Iterator_Vector
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
		vec_list.add("Red");
		vec_list.add("Green");
		vec_list.add("Blue");
		vec_list.add("Yellow");
		vec_list.add("Orange");
 
		Iterator itr = vec_list.iterator();
		System.out.println("Vector Elements are : ");
 
		while (itr.hasNext())
		{
			System.out.println(itr.next());
		}
	}
}

Output

Vector Elements are :
Red
Green
Blue
Yellow
Orange

Example Programs