且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不更新原始向量的情况下将一个向量复制到另一个向量?

更新时间:2022-11-04 10:04:23

。您所做的是将相同的向量分配给另一个变量:



之前:

 code> finished ------> [a,b,c,d] 

之后:

 完成------> [a,b,c,d] 
^
|
finished_copy --- /

这里是如何复制一个Vector的所有元素另一个:

  Vector< Allocated> finishedCopy = new Vector<>(finished); 

  Vector< Allocated> finishedCopy = new Vector<>(); 
finishedCopy.addAll(finished);

然而,这将创建两个不同的向量,其中包含对相同已分配实例的引用。如果你想要的是这些对象的副本,那么你需要创建显式副本。没有做副本,改变第一个列表中对象的状态也会改变它在第二个列表中的状态,因为这两个列表都包含对同一个对象的引用。



请注意:




  • 类别应以大写字母开头

  • 变量不应包含下划线, be camelCased

  • 不应再使用向量。 ArrayList应该是,因为Java 2.我们在Java 8。


I am copying a vector to another vector of same type.And modifying the copy vector but the original vector is also getting update I don't understand why?

Vector<allocated>finished_copy=new Vector<allocated>();
finished_copy=finished;

I am printing the value of original vector after and before modification

for(int k=0;k<finished.size();k++) {
        System.out.print(finished.elementAt(k).output);
        System.out.print(finished.elementAt(k).step);
        System.out.println();
}//some modification on finished_copy

And printing the original but both are different

Please help me in this

You're not doing any copy. All you're doing is assigning the same Vector to another variable:

Before:

finished ------> [a, b, c, d]

After:

finished ------> [a, b, c, d]
                 ^
                 |
finished_copy ---/

Here's how you would copy all the elements of a Vector into another one:

Vector<Allocated> finishedCopy = new Vector<>(finished);

or

Vector<Allocated> finishedCopy = new Vector<>();
finishedCopy.addAll(finished);

This, however, will create two different vectors containing references to the same Allocated instances. If what you want is a copy of those objects, then you need to create explicit copies. Without doing a copy, changing the state of an object in the first list will also change its state in the second one, since both lists contain references to the same ojects.

Note that:

  • classes should start with an uppercase letter
  • variables should not contain underscares, but be camelCased
  • Vector should not be used anymore. ArrayList should be, since Java 2. We're at Java 8.