I’d like to copy a vector to another. The problem is that if I change the vector v1, the second vector v2 is changing too. My goal is to keep the copy intact even if I change the source vector.
import java.util.Collections;
import java.util.Vector;
public class CopyElementsOfVectorToVectorExample {
public static void main(String[] args) {
//create first Vector object
Vector v1 = new Vector();
//Add elements to Vector
v1.add("1");
v1.add("2");
v1.add("3");
//create another Vector object
Vector v2 = new Vector(v1.size());
v2.setSize(v1.size());
Collections.copy(v2,v1);
System.out.println("After copy, Second Vector Contains : " + v2);
}}
How can I keep the second copy intact?
the problem is if I change the vector v1, the second v2 is changing too ...My goal is to keep the copy intact even if I change the source vectorThis is because
Collections.copy(v2,v1)make a sallow copy not deep copy.Make deep copy of your
Vector.Apologize for previous answer.
Edit:
I am assuming that your
vectoris containing objects of typeSerializable. With this approach you can get a deep copy of your collection.