How a Vector can be cloned in Java


A Vector can be cloned using the java.util.Vector.clone() method. This method does not take any parameters but returns a clone of the specified Vector instance as an object.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec1 = new Vector();
      vec1.add(7);
      vec1.add(3);
      vec1.add(5);
      vec1.add(9);
      vec1.add(2);
      Vector vec2 = (Vector) vec1.clone();
      System.out.println("The Vector vec1 elements are: " + vec1);
      System.out.println("The Vector vec2 elements are: " + vec2);
   }
}

The output of the above program is as follows −

The Vector vec1 elements are: [7, 3, 5, 9, 2]
The Vector vec2 elements are: [7, 3, 5, 9, 2]

Now let us understand the above program.

The Vector vec1 is created. Then Vector.add() is used to add the elements to vec1. Then vec1 is cloned using the Vector.clone() method into vec2. Then the elements of vec1 and vec2 are displayed. A code snippet which demonstrates this is as follows −

Vector vec1 = new Vector();
vec1.add(7);
vec1.add(3);
vec1.add(5);
vec1.add(9);
vec1.add(2);
Vector vec2 = (Vector) vec1.clone();
System.out.println("The Vector vec1 elements are: " + vec1);
System.out.println("The Vector vec2 elements are: " + vec2);

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jun-2020

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements