【发布时间】:2012-11-24 14:39:02
【问题描述】:
我正在尝试复制一个对象,然后将对其进行修改,而不更改原始对象。
我找到了this solution,似乎最好的方法是复制构造函数 - 据我了解,这会给我一个深层副本(与原始对象完全分开的对象)。
所以我尝试了。但是,我注意到当下面的代码执行时,它会影响之前复制它的所有对象。当我调用surveyCopy.take() 时,这将更改Survey 内部的值,它也会更改 selectedSurvey 内部的值。
public class MainDriver {
...
//Code that is supposed to create the copy
case "11": selectedSurvey = retrieveBlankSurvey(currentSurveys);
Survey surveyCopy = new Survey(selectedSurvey);
surveyCopy.take(consoleIO);
currentSurveys.add(surveyCopy);
break;
}
这是我的复制构造函数的代码:
public class Survey implements Serializable
{
ArrayList<Question> questionList;
int numQuestions;
String taker;
String surveyName;
boolean isTaken;
//Copy constructor
public Survey(Survey incoming)
{
this.taker = incoming.getTaker();
this.numQuestions = incoming.getNumQuestions();
this.questionList = incoming.getQuestionList();
this.surveyName = incoming.getSurveyName();
this.isTaken = incoming.isTaken();
}
}
那么问题到底是什么?复制构造函数不能那样工作吗?是不是我写错了?
【问题讨论】:
标签: java object constructor copy