I'm trying to copy each element from one ArrayList (av) to another one (copia). The thing is that they're copied by reference, so whenever I make any changes in the original one, the copy is modified as well. Of course, this behavior is not wanted. How should I write this method?
public void copiarArrayList(ArrayList<Articulo_Venta> copia, ArrayList<Articulo_Venta> av){
copia.clear();
for (int i = 0; i < av.size(); i++) {
copia.add(av.get(i));
}
}
Articulo_Venta has these fields:
int codigo;
String nombre;
float cantidad;
PS: I also tried the next:
copia = new ArrayList<Articulo_Venta>(av);
but it still has its elements pointing to the original ArrayList.
What you want is the deep copy. If your object contains only primitive you could use clone(), otherwise best way is to do manually:-
Make a constructor in your Articulo_Venta
class which takes another Articulo_Venta
object and initializes member variables.
Then change the code as:-
public void copiarArrayList(ArrayList<Articulo_Venta> copia, ArrayList<Articulo_Venta> av){
copia.clear();
for (int i = 0; i < av.size(); i++) {
copia.add(new Articulo_Venta(av.get(i)));
}
Also read here - how-do-you-make-a-deep-copy-of-an-object-in-java
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Articulo_Venta av : oldList) {
newList.add(av.clone());
}
clone should be correctly overriden in Articulo_Venta.
This is how you do it.
public class Articulo_Venta {
String a; //assuming you have these fields, then
Date d;
...
public Articulo_Venta clone(){
Articulo_Venta av = new Articulo_Venta();
av.a = this.a.clone();
av.d = this.d.clone();
...
return av;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With