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


i've been using arraylists on project of mine, , need create default arraylist can reset original 1 whenever want. so, copy original arraylist create default one. however, whenever modify on original, changes default one. how can make copy "static" , unchangeable?

here 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 array public void gravarlistadefault(){         this.listacompartimentosdefault=(arraylist<compartimento>)listacompartimentos.clone();     } 

note: don't know if can reason behind it, arraylist listacompartimentos has listaequipamentos. each "compartimento" there arraylist "listaequipamentos".

cloning means have 2 different lists, contents same. if change state of object inside first list, change in second list.

use copy-constructors , avoid clone() :

new arraylist(originallist)

clone() arraylists should avoided because if creates new instance, holds same elements. element changed on list changed on second one.

the code below create new instance new elements.

arraylist<object> clone = new arraylist<object>(); for(object o : originallist) clone.add(o.clone()); 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -