Write a Java program to add elements of a Vector to other Vector collection


The code you provided is written in Java and demonstrates how to add elements to vectors and combine two vectors. Here's a breakdown of what the code does:

  • Two Vector objects, vec_list1 and vec_list2, are created using the Vector class. In Java, Vector is a dynamic array-like data structure that can store elements of any type.
  • Several elements are added to vec_list1 using the add() method. These elements are strings representing fruits: "Apple", "Banana", "Orange", "Cherry", and "Mango".
  • Several elements are added to vec_list2 using the add() method. These elements are integers: 10, 20, 30, 40, and 50.
  • The contents of vec_list1 and vec_list2 are printed using System.out.println().
  • The addAll() method is used to add all elements from vec_list2 to vec_list1. This method appends all the elements of one vector to another.
  • The modified vec_list1 and vec_list2 are printed again to show the updated contents.

Source Code

import java.util.*;
public class Add_Elements
{
	public static void main(String[] args)
	{
		Vector vec_list1 = new Vector();
		Vector vec_list2 = new Vector();
 
		vec_list1.add("Apple");
		vec_list1.add("Banana");
		vec_list1.add("Orange");
		vec_list1.add("Cherry");
		vec_list1.add("Mango");
 
		vec_list2.add(10);
		vec_list2.add(20);
		vec_list2.add(30);
		vec_list2.add(40);
		vec_list2.add(50);
 
		System.out.println("Vector List 1 : " + vec_list1);
		System.out.println("Vector List 2 : " + vec_list2);
 
		vec_list1.addAll(vec_list2);
 
		System.out.println("Vector List 1 : " + vec_list1);
		System.out.println("Vector List 2 : " + vec_list2);
	}
}

Output

Vector List 1 : [Apple, Banana, Orange, Cherry, Mango]
Vector List 2 : [10, 20, 30, 40, 50]
Vector List 1 : [Apple, Banana, Orange, Cherry, Mango, 10, 20, 30, 40, 50]
Vector List 2 : [10, 20, 30, 40, 50]

Example Programs