Write a Java program to copy elements of Vector collection into an array


The code you provided demonstrates how to copy elements from a Vector into an array in Java using the copyInto method. Here's a breakdown of what the code does:

  • A Vector<String> object named vec_list is created.
  • An array of strings named vehicles with a size of 5 is initialized.
  • Elements "Apple", "Banana", "Cherry", "Orange", and "Mango" are added to vec_list using the add method.
  • The current contents of vec_list are printed using System.out.println.
  • The copyInto method is used to copy the elements from vec_list into the vehicles array.
  • The elements of the vehicles array are printed using a for-each loop, displaying each element on a separate line.

Source Code

import java.util.*;
public class Copy_Elements
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
 
		String vehicles[] = new String[5];
 
		vec_list.add("Apple");
		vec_list.add("Banana");
		vec_list.add("Cherry");
		vec_list.add("Orange");
		vec_list.add("Mango");
 
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.copyInto(vehicles);
 
		System.out.println("Array Elements : ");
		for (String v: vehicles)
		{
			System.out.println(" " + v);
		}
	}
}

Output

Vector Elements : [Apple, Banana, Cherry, Orange, Mango]
Array Elements :
 Apple
 Banana
 Cherry
 Orange
 Mango

Example Programs