Copying an object using a constructor, Java

杀马特。学长 韩版系。学妹 提交于 2019-12-14 04:07:38

问题


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:


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)



来源:https://stackoverflow.com/questions/3946668/copying-an-object-using-a-constructor-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!