Write a Java program to add elements of a vector to other vector collection at the specified position


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

  • Two Vector objects, vec_list1 and vec_list2, are created.
  • Elements "Apple", "Banana", "Orange", "Cherry", and "Mango" are added to vec_list1 using the add method.
  • Integers 10, 20, 30, 40, and 50 are added to vec_list2 using the add method.
  • The current 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 starting at index 2. This will insert the elements of vec_list2 in between "Orange" and "Cherry" in vec_list1.
  • The updated contents of vec_list1 and vec_list2 are printed again using System.out.println.

Source Code

import java.util.*;
public class AddElement
{
	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(2, 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, 10, 20, 30, 40, 50, Orange, Cherry, Mango]
Vector List 2 : [10, 20, 30, 40, 50]

Example Programs