Copy all elements from Vector to another Vector in Java
This example shows how to copy all elements from one vector to another vector. The procedure used in the code below modifies and replaces the second vector with the elements of the first vector with the corresponding elements. For example, if we copy v1 into v2 then the first element of v2 will be replaced by the first element of v1 and so on.In the following code we declare two vectors v1 and v2 and apply the method Collections.copy() which will make it easier for us to copy.
import java.util.Collections;Output:
import java.util.Vector;
public class Copy {
public static void main(String[] args) {
Vectorv1 = new Vector ();
v1.add("a");
v1.add("b");
v1.add("c");
v1.add("d");
v1.add("e");
Vectorv2 = new Vector (5);
v2.add("a2");
v2.add("b2");
v2.add("c2");
v2.add("d2");
v2.add("e2");
System.out.println("v2(before): "+v2);
Collections.copy(v2, v1);
System.out.println("v2(after): "+v2);
}
}
v2(before): [a2, b2, c2, d2, e2]
v2(after): [a, b, c, d, e]
Note: The Collections.copy() throws an exception if the second vector v2 is empty, or its size doesn't match the size of v1, because this method copies subscript by subscript without allocating memory and incrementing the capacity of v1. |