I wanted to ask cause i'm fairly new at this , is this the correct way of making a deep copy of the Document Object , i don't know if I implemented correctly the copying of the fields.
package model;
public class Document implements Cloneable {
//fields
private String author;
private String date;
private double versionID;
private String contents;
public Document(String author,String date,double versionID,String contents) {
this.author=author;
this.date=date;
this.versionID=versionID;
this.contents=contents;
}
//getters-setters
}
//making the deep-copy clone all obj ref to Document
@Override
public Object clone() throws CloneNotSupportedException {
Document doc =(Document)super.clone();
doc.author=this.author;
doc.date=this.date;
doc.versionID=this.versionID;
doc.contents=this.contents;
return doc;
}
}
Your object only has primitive types and immutable strings, so Document doc =(Document)super.clone();
is enough and you dont have to do the separate assignments.
But this is a bit risky, since should you ever add a mutable object to the fields, not doing a separate copy of that object will cause problems.
There are already extended discussions also on using some existing libraries to do deep copies, e.g as in here: How do you make a deep copy of an object in Java?