[英]Why can't I set a List of objects from similar classes in different packages
我有2個具有相同字段的相似類,但是它們位於不同的包中。 在遍歷源A類並復制數據之后,Java不允許我在目標B類上調用set方法將數據從A傳輸到B。
public class A { //reside in package A
public List<QuestionTemplate> qTemplateList;
}
public class QuestionTemplate { //reside in package A
public List<QuestionList> qList;
}
public class QuestionList { //reside in package A
public String questionText;
public String questionChoice;
}
public class B { //reside in package B
public List<QuestionTemplate> qTemplateList;
}
public class QuestionTemplate { //reside in package B
public List<QuestionList> qList;
}
public class QuestionList { //reside in package B
public String questionText;
public String questionChoice;
}
我嘗試遍歷A類列表並收集數據並創建一個ListCopy。 然后調用B類的set方法並發送剛從A類創建的ListCopy。
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.setQuestionTemplates(templateListCopy); // error on this line:
錯誤是:
setQuestionTemplates(List<A.QuestionTemplate>) in class A cannot be applied to (List<B.QuestionTemplate>)
現在做什么?
例如,您必須從程序包B中刪除QuestionList和QuestionTemplate,然后在類B中,您必須從程序包A中導入QuestionList和QuestionTemplate。
如果您想創建類似類的集合,建議您閱讀有關多態的信息:)
例
就像@ luk2302所說的那樣,您應該創建類QuestionTemplate,然后實現兩個類。
第一:
QuestionTemplateA擴展了QuestionTemplate
第二:
QuestionTemplateB擴展了QuestionTemplate
然后您可以創建QuestionTemplate的新集合,並在其中放置兩個類
List<QuestionTemplate> list = new ArrayList<>();
QuestionTemplateA a = new QuestionTemplateA();
QuestionTemplateB b = new QuestionTemplateB();
list.add(a);
list.add(b);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.