Reputation: 535
I have two classes, say Class Foo , and Class Boo.Foo class contains an arraylist of Boo class. I need to create a deep copy of Foo class, and I'm creating arraylist of Foo itself. How can I accomplish this.
Class Foo{
ArrayList<Boo> boovar = new ArrayList<Boo>();
}
Class Boo{
int x;
void add_x(int y)
{
x=y;
}
}
ArrayList<Foo> foovar = new ArrayList<Foo>();
..adding elements to foovar.
now I want to create an ArrayList foovar1 of type Foo, such that it is a deep copy of the objects in foovar. ie, if I modify a boo object in foovar, like deleting x or adding elements, it should not be reflected when i access foovar1.
I know deep copying has been beaten to death, but I really couldn't find articles telling me how to do this. Could someone show me how with a code?
EDIT:
Im trying to create a copy constructor within Foo, like one of the comments mentioned, but I'm really at a loss on how to copy the Boo arraylist to another through the constructor in Foo. Not to mention how I'm going to loop the instances of Foo in the arraylist to create copies of that as well. Any help would be really appreciated!
Upvotes: 0
Views: 141
Reputation: 12837
EDIT:
List<Boo> newCopy = new ArrayList<Boo>(boovar);
newCopy.addAll(boovar);
..provided the elements of boovar are immutable. If not, you should utilize the clone() method on Boo class.
Upvotes: 0
Reputation:
First, you need to make a copy Constructor in your Boo class:
Class Boo{
int x;
//copy constructor
public Boo (Boo sourceBoo){
x = sourceBoo.x;
}
}
with the above, you can make a copy constructor in Foo class that copies the array of Boos contained in it:
Class Foo{
ArrayList<Boo> boovar = new ArrayList<Boo>();
//copy constructor
public Foo(Foo sourceFoo){
for (Boo aBoo:sourceFoo.boovar){
boovar.add(new Boo(aBoo));
}
}
}
now, you can loop over your array of Foo(s) and copy them one by one into a new array. you can define a method to do that:
public ArrayList<Foo> deepCopyFooList(ArrayList<Foo> sourceArray){
ArrayList<Foo> targetList = new ArrayList<Foo>();
for (Foo aFoo:sourceArray){
targetList.add(new Foo(aFoo));
}
return targetList;
}
so to copy your array you would:
ArrayList<Foo> foovar = new ArrayList<Foo>();
ArrayList<Foo> foovarCopy = deepCopyFooList(foovar);
Upvotes: 1