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