GorillaSpoon
GorillaSpoon

Reputation: 25

Deep Copy Constructor in Java

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

Upvotes: 1

Views: 1190

Answers (2)

omerfar23
omerfar23

Reputation: 34

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

    }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201477

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

Upvotes: 2

Related Questions