通过复制构造函数在 Java 中复制对象而不影响原始对象
我正在尝试复制一个对象,然后将对其进行修改,而不更改原始对象.
I'm trying to copy an Object, which will then be modified, without changing the original object.
我找到了 这个解决方案,它似乎是最好的方法将是一个复制构造函数 - 据我了解,这会给我一个深层副本(与原始对象完全分开的对象).
I found this solution and it seemed the best approach would be a copy constructor - from my understanding, this would give me a deep copy (a completely separate object from the original).
所以我尝试了.但是,我注意到当下面的代码执行时,它会影响之前复制它的所有对象.当我调用 surveyCopy.take()
时,它会改变 Survey
内的值,它也会改变 selectedSurvey 内的值.
So I tried that. However, I've noticed that when the following code executes, it's effecting all previous objects from which it was copied. When I call surveyCopy.take()
, which will change values inside of the Survey
, it's also changing the values inside of 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;
}
这是我的复制构造函数的代码:
and here is code for my copy constructor:
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();
}
}
那么问题到底是什么?复制构造函数不能那样工作吗?是不是我写错了?
So what exactly is the issue? Does a copy constructor not work that way? Is the way I coded it wrong?
推荐答案
这是问题所在,在你的复制构造函数中:
This is the problem, in your copy constructor:
this.questionList = incoming.getQuestionList();
这只是将 reference 复制到列表中.两个对象仍将引用同一个对象.
That's just copying the reference to the list. Both objects will still refer to the same object.
你可以使用:
this.questionList = new ArrayList<Question>(incoming.getQuestionList());
创建原始列表的副本 - 但如果 Question
本身是可变的,这仍然不够好.在这种情况下,您必须创建每个 Question
对象的副本以实现完全隔离.
to create a copy of the original list - but this is still not good enough if Question
itself is mutable. In that case, you'd have to create a copy of each Question
object to achieve total isolation.
您的其他字段没问题,因为它们要么是原语,要么是对 String
的引用(这是不可变的,允许您安全地共享引用).
Your other fields are okay, as they're either primitives or references to String
(which is immutable, allowing you to share references safely).
相关文章