views:

39

answers:

1

So lets say I want to make a deep copy of an object, but using its contsructor. So I have:

public class PositionList {
    private Position[] data = new Position[0];
    private int size = 0;

public PositionList(PositionList other, boolean deepCopy) {
    if (deepCopy==true){
        size=other.getSize();
        for (int i=0;i<data.length;i++)
        data[i]=other.data[i];
    }
    else {
        data=other.data;
        size = other.size;

And so say I have this being called:

PositionList list = new PositionList();
PositionList acopy = new PositionList(list, true);

What I am doing, however, is incorrect, and Im not sure why..

+1  A: 

The problem lies in your deep copy logic:

size=other.getSize();
for (int i=0;i<data.length;i++)
    data[i]=other.data[i];

You are setting the size field (which is redundant with the data array) but are not assigning a new array to the data field, which is presumably the whole point of your "deep" copy. You should initialize data to the other's size (or other.data.length):

data = new Position[other.data.length];
for (int i=0;i<data.length;i++)
    data[i]=other.data[i];

(And get rid of size all together)

Kirk Woll
Wait why would I get rid of size?
fprime
@fprime, what value would `size` *ever* contain that doesn't match `data.length`?
Kirk Woll