Write a Java program to create a clone of a Vector collection


The code you provided is written in Java and demonstrates how to create a clone of a Vector using the clone() 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 Create_Clone: This line declares a public class named Create_Clone.
  • 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.
  • Vector clone_vec = (Vector) vec_list.clone();: This line creates a clone of the vec_list vector by calling the clone() method on it. The clone() method creates a shallow copy of the vector, meaning that the elements themselves are not cloned, but the new vector refers to the same elements.
  • System.out.println("Original Vector Elements : " + vec_list); : This line prints the elements of the original vector by concatenating the string "Original Vector Elements :" with the vector vec_list. The println function automatically converts the vector to a string representation.
  • System.out.println("Clone Vector Elements : " + clone_vec); : This line prints the elements of the clone vector by concatenating the string "Clone Vector Elements :" with the vector clone_vec.

Source Code

import java.util.*;
public class Create_Clone
{
	public static void main(String[] args)
	{
		Vector <Integer> vec_list = new Vector <Integer>();
 
		for (int i = 1; i <= 10; i++)
		{
			vec_list.add(i);
		}
 
		Vector clone_vec = (Vector) vec_list.clone();
 
		System.out.println("Original Vector Elements : " + vec_list);
		System.out.println("Clone Vector Elements : " + clone_vec);
	}
}

Output

Original Vector Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Clone Vector Elements : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example Programs