1 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
此代碼需要 Java 7 或更高版本。
選項(xiàng) A 通過(guò)迭代手動(dòng)復(fù)制數(shù)據(jù):
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;
選項(xiàng) B 修改類(lèi)并添加復(fù)制方法,使實(shí)現(xiàn)代碼不那么混亂:
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;
}
}
執(zhí)行:
A a = new A();
..
B b = new B();
b.qTemplateList = a.copy().qTemplateList;

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
添加回答
舉報(bào)