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

StackOverflow https://stackoverflow.com/questions/16562881

  •  29-05-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

clone() for ArrayLists should be avoided because even if it creates a new List instance, it holds 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());

OTHER TIPS

this.listaCompartimentosDEFAULT = new ArrayList<Compartimento>(
            listaCompartimentos);

I would suggest to clone each object . Make your Compartimentoclass implements Cloneable. And clone each object in the List and add to the other List.

for(Compartimento c : this.listaCompartimentos) {
    this.listaCompartimentosDEFAULT.add(c.clone());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top