How to copy or clone a vector?

 In this example we will see how to copy all the elements of a Vector to another Vector. This process replaces the existing elements of the second vector with the corresponding element of first vector.

In the below code we have two vectors v1 & v2 and we are copying all the elements of v1 to v2 using clone() method.

package Vector;

import java.util.Vector;

public class VectorCloneExample {

  public static void main(String[] args) {
    Vector<String> v1 = new Vector<String>();
         //Adding elements to the first Vector
    v1.add("ABC");
    v1.add("BCE");
    v1.add("CDE");
    v1.add("DEF");
         Vector<String> v2 = new Vector<String>();
         //Adding elements to the second Vector
         v2.add("1st");
         v2.add("2nd");
         v2.add("3rd");
         v2.add("4th");
         v2.add("5th");
         v2.add("6th");
         
          v2 = (Vector<String>) v1.clone();
          System.out.println("Cloned vector:"+v2);
         

  }

}

Output:

Cloned vector:[ABC, BCE, CDE, DEF]

 

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site.
I welcome and value your comments, suggestions and corrections.

1109total visits,1visits today

The only business I know is learning new technology and spreading the knowledge. I believe sharing is learning. This is my prime reason to build this site. I welcome and value your comments, suggestions and corrections.