How to copy elements from an ArrayList to another

2019-07-17 06:55发布

问题:

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 has these fields:

int codigo;
String nombre;
float cantidad;

PS: I also tried the next:

copia = new ArrayList<Articulo_Venta>(av);

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

回答1:

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

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

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



回答2:

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

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

clone should be correctly overriden in 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;
}
}


回答3:

Create a new constructor in your class 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);
   });
}