javaarraylistcloning

How to copy an ArrayList that cannot be influenced by the original ArrayList changes?


I've been using ArrayLists on a project of mine, and I need to create a default ArrayList so I can reset the original one whenever I want. So, I copy the original ArrayList to create the default one. However, whenever I modify something on the original, it also changes the default one. How can I make the copy "static" and unchangeable?

Here is my code: (It's in portuguese)

private ArrayList<Compartimento> listaCompartimentos;
private ArrayList<Compartimento> listaCompartimentosDEFAULT;

public Simulador() {
        this.listaCompartimentos = new ArrayList<>();
        this.listaCompartimentosDEFAULT=new ArrayList<>();
    }

//Copy of the array
public void gravarListaDefault(){
        this.listaCompartimentosDEFAULT=(ArrayList<Compartimento>)listaCompartimentos.clone();
    }

Note: I don't know if it can be the reason behind it, but the ArrayList listaCompartimentos has a listaEquipamentos. For each "Compartimento" there is an ArrayList "listaEquipamentos".


Solution

  • clone() for ArrayLists should be avoided because even if it creates a new List instance, it holds references to the same elements. So an element changed on the first List will also be changed on the second one. Two different objects holding the same references.

    The code below will create a new instance with new elements.

    ArrayList<Object> realClone = new ArrayList<Object>();
    for(Object o : originalList)
       realClone.add(o.clone());