1

I need to create a deep copy constructor, but I'm not quite sure how with my given program. My program doesn't use any other fields other than an array of byte. My instructions for the constructor were simply:"Copy constructor; a deep copy should be performed."

public class AdditionOnlyInt implements BigInt{

    private byte[] d;


    public AdditionOnlyInt(AdditionOnlyInt a){
        this.d = a.d;
    }
}
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
GorillaSpoon
  • 25
  • 1
  • 5
  • 4
    "Deep copy" means allocating a new array of the same size and copying the values over. – T.C. Oct 07 '14 at 00:20
  • To test whether you have done a deep copy correctly, changing an element in the array of the first object should have no effect on the second object. – BevynQ Oct 07 '14 at 00:21
  • and even you can read this http://stackoverflow.com/questions/6182565/java-deep-copy-shallow-copy-clone – Kick Buttowski Oct 07 '14 at 00:22
  • 1
    So to deep copy a, I would create a new array of bytes within the constructor and use a loop to copy the elements from "d" array to the new array? – GorillaSpoon Oct 07 '14 at 00:23
  • @GorillaSpoon Yes, you've got it. However, as Elliott's answer says, there are methods to do the copy for you so you don't have to write your own loop, if your instructor allows you to use a library method (I'm assuming this is homework). – ajb Oct 07 '14 at 00:33
  • @ajb Yes it is for homework. Our class received this program back to rework and the vast majority of us had our copy constructors incorrect. Thank you for your answers, they've helped me understand something I thought was much more complex than it actually was. – GorillaSpoon Oct 07 '14 at 00:45

2 Answers2

2

You could change your constructor from

public AdditionOnlyInt(AdditionOnlyInt a){
  this.d = a.d;
}

to use Arrays.copyOf(byte[], int)

public AdditionOnlyInt(AdditionOnlyInt a){
  this.d = (a != null && a.d != null) ? Arrays.copyOf(a.d, a.d.length) : null;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

A deep copy constructor usually means that you need to copy of the content of the provided object to the "this" object. For example:

 class Example{
    private double parameter_one;
    private double parameter_two

    // A constructor 
    public Example(double p1, double p2) {
        this.parameter_one = p1;
        this.parameter_two = p2;
    }

    // copy constructor
    Example(Example c) {
        System.out.println("Copy constructor called");
        parameter_one = c.p1;
        parameter_two = c.p2;
    }
}





public class Main {

    public static void main(String[] args) {

        // Normal Constructor
        Example ex = new Example(10, 15);

        // Following involves a copy constructor call
        Example ex2 = new Example(ex);   

    }
}
omerfar23
  • 34
  • 3