如何不通过引用将元素从 ArrayList 复制到另一个? [英] How to copy elements from an ArrayList to another one NOT by reference?
问题描述
我正在尝试将每个元素从一个 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-do-you-make-a-deep-copy-of-an-object-in-java
这篇关于如何不通过引用将元素从 ArrayList 复制到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!