Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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.

like image 549
Ezequiel Berto Avatar asked Dec 11 '22 13:12

Ezequiel Berto


2 Answers

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

like image 151
Mangat Rai Modi Avatar answered Dec 26 '22 00:12

Mangat Rai Modi


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;
}
}
like image 26
Faraz Avatar answered Dec 25 '22 22:12

Faraz