Home »
Java »
Java Programs
Java program to add elements of a Vector to other Vector collection
Java example to add elements of a vector to other vector collection.
Submitted by Nidhi, on May 19, 2022
Problem statement
In this program, we will create two Vector collection with a different type of elements. Then we will add a vector collection to another vector using the addAll() method.
Java program to add elements of a Vector to other Vector collection
The source code to add elements of a vector to other vector collection is given below. The given program is compiled and executed successfully.
// Java program to add elements of a vector to
// other vector collection
import java.util.*;
public class Main {
public static void main(String[] args) {
Vector vec1 = new Vector();
Vector vec2 = new Vector();
vec1.add(10);
vec1.add(20.5);
vec1.add(true);
vec1.add("Hello World");
vec2.add("A");
vec2.add("B");
vec2.add("C");
vec2.add("D");
System.out.println("Vector Vec1 : " + vec1);
System.out.println("Vector Vec2 : " + vec2);
vec1.addAll(vec2);
System.out.println("\nVector Vec1 : " + vec1);
System.out.println("Vector Vec2 : " + vec2);
}
}
Output
Vector Vec1 : [10, 20.5, true, Hello World]
Vector Vec2 : [A, B, C, D]
Vector Vec1 : [10, 20.5, true, Hello World, A, B, C, D]
Vector Vec2 : [A, B, C, D]
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 two Vector collections vec1, vec2 and add elements to them. Then we added vec2 vector to vec1 using addAll() method. After that, we printed the updated vectors.
Java Vector Class Programs »