如何不通过引用将元素从ArrayList复制到另一个? [英] How to copy elements from an ArrayList to another one NOT by reference?

查看:143
本文介绍了如何不通过引用将元素从ArrayList复制到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将每个元素从一个ArrayList(av)复制到另一个(copia).事实是,它们是通过引用复制的,因此,只要我对原始副本进行了任何更改,副本也将被修改.当然,不需要这种行为.我应该怎么写这个方法?

I'm trying to copy each element from one ArrayList (av) to another one (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具有以下字段:

Articulo_Venta has these fields:

int codigo;
String nombre;
float cantidad;

PS:我也尝试了下一个:

PS: I also tried the next:

copia = new ArrayList<Articulo_Venta>(av);

但它仍然具有指向原始ArrayList的元素.

but it still has its elements pointing to the original ArrayList.

推荐答案

您想要的是深层副本.如果您的对象仅包含原始对象,则可以使用clone(),否则最好的方法是手动执行:-

What you want is the deep copy. If your object contains only primitive you could use clone(), otherwise best way is to do manually:-

Articulo_Venta类中构造一个构造函数,该构造函数采用另一个Articulo_Venta对象并初始化成员变量.

Make a constructor in your Articulo_Venta class which takes another Articulo_Venta object and initializes member variables.

然后将代码更改为:-

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)));
        }

也请在这里阅读- how您是否在Java中制作了对象的深层副本

这篇关于如何不通过引用将元素从ArrayList复制到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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