如何在不更新原始向量的情况下将一个向量复制到另一个向量? [英] How do I copy one vector to another vector in Java without updating the original vector?

查看:213
本文介绍了如何在不更新原始向量的情况下将一个向量复制到另一个向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在修改之前和之前打印原始向量的值

  for(int k = 0; k  System.out.print(finished.elementAt输出); 
System.out.print(finished.elementAt(k).step);
System.out.println();
} //对finished_copy进行一些修改

并打印原件, p>

请帮助我

解决方案

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



之前:

 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.

这篇关于如何在不更新原始向量的情况下将一个向量复制到另一个向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆