问题
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".
回答1:
Cloning means you have 2 different lists, but their contents are the same. If you change the state of an object inside the first list, it will change in the second list.
Use the copy-constructors and avoid clone()
:
new ArrayList(originalList)
Clone() for arraylists should be avoided because even if it creates a new instance, it holds the same elements. So an element which is changed on a list will be changed on the second one.
The code below will create a new instance with new elements.
ArrayList<Object> clone = new ArrayList<Object>();
for(Object o : originalList)
clone.add(o.clone());
回答2:
this.listaCompartimentosDEFAULT = new ArrayList<Compartimento>(
listaCompartimentos);
回答3:
I would suggest to clone
each object . Make your Compartimento
class 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());
}
来源:https://stackoverflow.com/questions/16562881/how-to-copy-an-arraylist-that-cannot-be-influenced-by-the-original-arraylist-cha