Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Prototype , making a deep copy

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;
    }   

}
like image 454
DavidDunn Avatar asked Jun 21 '26 00:06

DavidDunn


1 Answers

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?

like image 103
awagen Avatar answered Jun 22 '26 15:06

awagen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!