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

2022-01-20 00:00:00 复制 vector java

我正在将一个向量复制到另一个相同类型的向量.并且修改了复制向量但原始向量也在更新我不明白为什么?

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

和打印原件但两者不同

请帮帮我

推荐答案

你没有做任何拷贝.您所做的只是将相同的 Vector 分配给另一个变量:

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

之前:

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

之后:

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

以下是将 Vector 的所有元素复制到另一个 Vector 中的方法:

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

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

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.

注意:

  • 类应以大写字母开头
  • 变量不应包含下划线,而应为驼峰式
  • 向量不应再使用.ArrayList 应该是,因为 Java 2.我们在 Java 8.

相关文章