简体   繁体   English

如何通过引用将元素从ArrayList复制到另一个?

[英]How to copy elements from an ArrayList to another one NOT by reference?

I'm trying to copy each element from one ArrayList (av) to another one (copia). 我正在尝试将每个元素从一个ArrayList(av)复制到另一个(copia)。 The thing is that they're copied by reference, so whenever I make any changes in the original one, the copy is modified as well. 问题在于它们是通过引用复制的,因此每当我对原始版本进行任何更改时,副本也会被修改。 Of course, this behavior is not wanted. 当然,这种行为不是必需的。 How should I write this method? 我应该怎么写这个方法?

public void copiarArrayList(ArrayList<Articulo_Venta> copia, ArrayList<Articulo_Venta> av){
    copia.clear();
    for (int i = 0; i < av.size(); i++) {
        copia.add(av.get(i));
    }
}

Articulo_Venta has these fields: Articulo_Venta有以下几个字段:

int codigo;
String nombre;
float cantidad;

PS: I also tried the next: PS:我也试过了下一个:

copia = new ArrayList<Articulo_Venta>(av);

but it still has its elements pointing to the original ArrayList. 但它的元素仍然指向原始的ArrayList。

What you want is the deep copy. 你想要的是深拷贝。 If your object contains only primitive you could use clone(), otherwise best way is to do manually:- 如果您的对象只包含原语,则可以使用clone(),否则最好的方法是手动执行: -

Make a constructor in your Articulo_Venta class which takes another Articulo_Venta object and initializes member variables. Articulo_Venta类中创建一个构造函数,该构造函数接受另一个Articulo_Venta对象并初始化成员变量。

Then change the code as:- 然后将代码更改为: -

public void copiarArrayList(ArrayList<Articulo_Venta> copia, ArrayList<Articulo_Venta> av){
        copia.clear();
        for (int i = 0; i < av.size(); i++) {
            copia.add(new Articulo_Venta(av.get(i)));
        }

Also read here - how-do-you-make-a-deep-copy-of-an-object-in-java 也可以在这里阅读 - 如何在java中创建一个对象的深层副本

Cloning the objects before adding them. 在添加对象之前克隆对象。 For example, instead of newList.addAll(oldList); 例如,而不是newList.addAll(oldList);

for(Articulo_Venta av : oldList) {
    newList.add(av.clone());
}

clone should be correctly overriden in Articulo_Venta. 克隆应该在Articulo_Venta中正确覆盖。

This is how you do it. 这就是你如何做到的。

public class Articulo_Venta {

String a;  //assuming you have these fields, then
Date d;
...

public Articulo_Venta clone(){
    Articulo_Venta  av = new Articulo_Venta();
    av.a = this.a.clone();
    av.d = this.d.clone();
    ...
    return av;
}
}

Create a new constructor in your class Articulo_Venta. 在你的班级Articulo_Venta中创建一个新的构造函数。

public Articulo_Venta(int codigo, String number, float candidad)
{
  this.codigo = codigo;
  this.number = number;
  this.candidad = candidad;
}

public void copiarArrayList(List<Articulo_Venta> copia, List<Articulo_Venta> av)
{
   av.stream().forEach(t -> {
     Articulo_Venta newObj = new Articulo_Venta(t.getCodigo(), t.getNumber(), t.getCandidad());
     copia.add(newObj);
   });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM