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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 19:19:26

问题


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 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());
}


来源:https://stackoverflow.com/questions/16562881/how-to-copy-an-arraylist-that-cannot-be-influenced-by-the-original-arraylist-cha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!