1 回答
TA贡献1804条经验 获得超7个赞
此代码需要 Java 7 或更高版本。
选项 A 通过迭代手动复制数据:
A a = new A();
..
List<QuestionTemplate> templateListCopy = new LinkedList<>();
for (QuestionTemplate template : a.qTemplateList) {
List<QuestionList> questionListCopy = new LinkedList<>();
for (QuestionList question : template.qList) {
QuestionList questionCopy = new QuestionList();
questionCopy.questionText = question.questionText;
questionCopy.questionChoice = question.questionChoice;
questionListCopy.add(questionCopy);
}
QuestionTemplate questionTemplateCopy = new QuestionTemplate();
questionTemplateCopy.qList = questionListCopy;
templateListCopy.add(questionTemplateCopy);
}
B b = new B();
b.qTemplateList = templateListCopy;
选项 B 修改类并添加复制方法,使实现代码不那么混乱:
class A {
public List<QuestionTemplate> qTemplateList;
public A copy() {
A copy = new A();
List<QuestionTemplate> questionTemplateListCopy = new ArrayList<>(qTemplateList.size());
for (QuestionTemplate questionTemplate : qTemplateList) {
questionTemplateListCopy.add(questionTemplate.copy());
}
copy.qTemplateList = questionTemplateListCopy;
return copy;
}
}
class QuestionTemplate {
public List<QuestionList> qList;
public QuestionTemplate copy() {
QuestionTemplate copy = new QuestionTemplate();
List<QuestionList> qListCopy = new ArrayList<>(qList.size());
for (QuestionList questionList : qList) {
qListCopy.add(questionList.copy());
}
copy.qList = qListCopy;
return copy;
}
}
class QuestionList {
public String questionText;
public String questionChoice;
public QuestionList copy() {
QuestionList copy = new QuestionList();
copy.questionText = questionText;
copy.questionChoice = questionChoice;
return copy;
}
}
执行:
A a = new A();
..
B b = new B();
b.qTemplateList = a.copy().qTemplateList;
添加回答
举报