Search code examples
javaarraylistconstructorpass-by-value

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.


Solution

  • 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