Copying an object using a constructor, Java
So lets say I want to make a deep copy of an object, but using its contsructor. So I have:
public class PositionList {
private 开发者_如何学CPosition[] 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..
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)
精彩评论