Write a Java program to get elements from Vector collection based on an index


The code you provided demonstrates how to retrieve and iterate over the elements of a Vector using the get method and a for loop in Java. Here's a breakdown of what the code does:

  • A Vector<String> object named vec_list is created.
  • An integer variable i is initialized with a value of 0.
  • Elements "Grapes", "Banana", "Apple", "Cherry", "Orange", and "Mango" are added to vec_list using the add method.
  • The string "Vector Elements : " is printed using System.out.println.
  • The for loop is used to iterate over the elements of vec_list. It starts from index 0 and continues until i is less than the size of vec_list.
  • Inside the loop, the get method is used to retrieve the element at index i from vec_list, and it is printed using System.out.println.
  • The loop continues until all elements of vec_list have been printed.

Source Code

import java.util.*;
public class GetElements
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
		int i = 0;
		vec_list.add("Grapes");
		vec_list.add("Banana");
		vec_list.add("Apple");
		vec_list.add("Cherry");
		vec_list.add("Orange");
		vec_list.add("Mango");
 
		System.out.println("Vector Elements : ");
		for (i = 0; i < vec_list.size(); i++)
		{
			System.out.println(" " + vec_list.get(i));
		}
	}
}

Output

Vector Elements :
 Grapes
 Banana
 Apple
 Cherry
 Orange
 Mango

Example Programs