2

What I would like to do is to define a copy constructor which takes A as an argument and it initializes the new A to be a deep copy of argument A

public class A<E extends Comparable<? super E>> implements B<E> 
{
    private A a;
    private E[] hArray;

    // What I tried .... my copy constructor

    public A(A other)
    {
         this.a = other;  // deep copy
    }
}

Is this the right way of doing deep copy through copy constructor??

3
  • Just to clarify, do you want 'this.a' to be a deep copy of 'other', or do you want 'this' to be a deep copy of 'other'? Commented Nov 23, 2012 at 1:59
  • hm new A to be a deep copy of argument A.. Commented Nov 23, 2012 at 2:03
  • Ok, then my answer below still stands. Commented Nov 23, 2012 at 2:04

2 Answers 2

4

That's not a deep copy. You are just storing the reference to the other object.

Try this:

public A(A other) {
    if(other.a != null) {
        this.a = new A(other.a);
    }
    if(other.hArray != null) {
        this.hArray = new E[other.hArray.length];
        for(int index = 0; index < other.hArray.length; index++) {
            this.hArray[index] = other.hArray[index].clone();
        }
    }
}

This assumes that E also has a copy constructor that performs a deep copy. Plus I just noticed that E is a generic, so my code might not work correctly for that (but the idea is there).

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, I think the best way might be to put the restriction that E implements Cloneable if possible... then you could just go this.hArray[index] = other.hArray[index].clone(); - but of course that doesn't guarantee a deep copy...
All Java arrays implement a public clone(), you could use that to initially copy hArray.
But that wouldn't be deep copying the E objects. I think @Jeff got it right with cloning the individual elements. I've edited my answer.
1

You can't just assign if you want a deep copy - that's not what deep copy means. You'd need to go:

public A(A other)
{
    if(other != null) {
        this.a = new A(other.a);  // deep copy
    } else {
        this.a = null;
    }
}

That's recursive copying, and you could wind up with all kinds of infinite loops, though. Also, you'd need to deep copy E somehow, and those generics are kind of boggling my mind, so I won't try to speculate on how you might do that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.