Write a Java program to insert an item into Vector collection at the specified index


The code you provided is written in Java and demonstrates how to insert an item at a specific index in a Vector using the add() method. Here's an explanation of the code:

  • import java.util.*;: This line imports the java.util package, which contains the Vector class and other utility classes.
  • public class Insert_Item: This line declares a public class named Insert_Item.
  • public static void main(String[] args): This is the main method where the execution of the program starts. It takes an array of strings as command line arguments.
  • Vector<Integer> vec_list = new Vector<Integer>();: This line declares and initializes a Vector object named vec_list that can store Integer values. Note that using generics (<Integer>) is not necessary in newer versions of Java.
  • for (int i = 1; i <= 10; i++): This line starts a for loop with the loop variable i initialized to 1, and it continues as long as i is less than or equal to 10. After each iteration, i is incremented by 1.
  • vec_list.add(i);: Inside the for loop, this line adds the value of i to the vector vec_list.
  • System.out.println("Vector Elements : " + vec_list);: This line prints the elements of the vector by concatenating the string "Vector Elements :" with the vector vec_list. The println function automatically converts the vector to a string representation.
  • vec_list.add(2, 100);: This line inserts the value 100 at index 2 in the vector vec_list using the add() method. The existing elements at and after index 2 are shifted to the right to accommodate the new element.
  • System.out.println("Vector Elements After Insertion : "+vec_list); : This line prints the elements of the vector after the insertion using the add() method.

Source Code

import java.util.*;
public class Insert_Item
{
	public static void main(String[] args)
	{		
		Vector <Integer> vec_list = new Vector <Integer>();
 
		for (int i = 1; i <= 10; i++)
		{
			vec_list.add(i);
		}		
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.add(2, 100);
 
		System.out.println("Vector Elements After Insertion : "+vec_list);
	}
}

Output

Vector Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Vector Elements After Insertion : [1, 2, 100, 3, 4, 5, 6, 7, 8, 9, 10]

Example Programs