1

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

Carlito
  • 13
  • 3

3 Answers3

6

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());
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
aran
  • 10,978
  • 5
  • 39
  • 69
  • 2
    @AsierAranbarri Cloning does create a shallow copy. It says in the [docs](http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#clone%28%29) – NilsH May 15 '13 at 10:44
  • The thing is: In my main class, using the respective object that contains these two ArrayLists, I fill the original one, only THEN I clone it. These two ArrayList both belong to the class "Simulador" so, you are telling me to create two "Simulador" if I have to use a copy-constructor? – Carlito May 15 '13 at 10:48
  • You have to. When you clone a list, you are creating a new list but NOT new elements. – aran May 15 '13 at 10:49
  • 4
    Seems like `new ArrayList(originalList)` also creates a shallow copy, with references identical to `originalList`. – NilsH May 15 '13 at 10:49
2
this.listaCompartimentosDEFAULT = new ArrayList<Compartimento>(
            listaCompartimentos);
johnchen902
  • 9,531
  • 1
  • 27
  • 69
2

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());
}
AllTooSir
  • 48,828
  • 16
  • 130
  • 164