Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Clarification regarding deep cloning/deep copy

807569Jun 14 2006 — edited Jun 15 2006
Hi,

While performing deep copy of an object should all the subobject that the parent object constitute also constitute the clone method.
For Eg:
I have a class called Document and a class called Field. Document constitutes of List<Field> fields. Field class has a String fieldName as its member variable.

I need to perform a deep copy of Document object. Should Field class also implement the clone method or can I create field objects in the documents clone method and fill these fields with values from the existing field list to form a new Document with these new fields.

Or do I call clone() method on each field to get a new field object and
add it to the new Document object that I am creating in the clone() method .
//First approach
public Document clone(){
Document doc = new Document();
List<Field> fields = doc.getFields()
Field newField = null;
for(Field f: fields){
    newField = new Field();
    newField.setName(f.getName());
   doc.addField(newField);
}
return doc;
}


//Second Approach
public Document clone(){
Document doc = new Document();
List<Field> fields = doc.getFields()
Field newField = null;
for(Field f: fields){
    newField = f.clone()
   doc.addField(newField);
}
return doc;
}
Please let me know which is a better approach and the standard coding
practise.

Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 13 2006
Added on Jun 14 2006
1 comment
155 views