• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to clone a object containing collection?  RSS feed

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

How to clone a object containing collection. here is my class structure


I tried to clone an object of this type. I implemented Cloneable interface and overridden clone method as follows


is there any better way to clone this collection?

Regards,
Ajay.
 
Pavan Sambare
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest way to clone an object is to serialize it and then deserialize it into a new reference. Only thing for this is that your class should implement Serializable.
 
Kannan Palani
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do it by cloning list also.

public Object clone()
{

//enclosed in a try catch block
ToBeCloned cln = (ToBeCloned) super.clone();
cln.names = (ArrayList)list.clone();
return cln;
}
 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
Thanks for your reply.
public Object clone()
{

//enclosed in a try catch block
ToBeCloned cln = (ToBeCloned) super.clone();
cln.names = (ArrayList)list.clone();
return cln;
}


This will return only a shallow copy of an array list. i need all the objects in the list to be cloned (recursively).

Thanks,
Ajay.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!