Home »
Java »
Java Programs
Java program to copy elements of Vector collection into an array
Given a Vector collection, we have to copy its elements into an array.
Submitted by Nidhi, on May 20, 2022
Problem Solution:
In this program, we will create a Vector collection with string elements. Then we will copy elements of the Vector collection into an array using the copyInto() method.
Program/Source Code:
The source code to copy elements of Vector collection into an array is given below. The given program is compiled and executed successfully.
// Java program to copy elements of Vector collection
// into an array
import java.util.*;
public class Main {
public static void main(String[] args) {
Vector < String > vec = new Vector < String > ();
String vehicles[] = new String[5];
vec.add("CAR");
vec.add("BUS");
vec.add("BIKE");
vec.add("TRUCK");
System.out.println("Vector elements: " + vec);
vec.copyInto(vehicles);
System.out.println("Array elements: ");
for (String v: vehicles)
System.out.println(" " + v);
}
}
Output:
Vector elements: [CAR, BUS, BIKE, TRUCK]
Array elements:
CAR
BUS
BIKE
TRUCK
null
Explanation:
In the above program, we imported the "java.util.*" package to use the Vector class. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created a Vector collection vec and add elements to it. Then we create an array of strings. After that, we copied the elements of vector collection into a string array using the copyInto() method. After that, we printed the elements of the array.
Java Vector Class Programs »