[英]Why can't I set a List of objects from similar classes in different packages
I have 2 similar classes with identical fields but they reside in different packages. 我有2个具有相同字段的相似类,但是它们位于不同的包中。 After walking the source A class and copy the data, Java won't allow me to call a set method on target B class to transfer data from A to B.
在遍历源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;
}
I tried walking the the A class list and gather the data and created a ListCopy. 我尝试遍历A类列表并收集数据并创建一个ListCopy。 Then call B class set method and send in the ListCopy just created from A class.
然后调用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:
the error is: 错误是:
setQuestionTemplates(List<A.QuestionTemplate>) in class A cannot be applied to (List<B.QuestionTemplate>)
What to do now? 现在做什么?
例如,您必须从程序包B中删除QuestionList和QuestionTemplate,然后在类B中,您必须从程序包A中导入QuestionList和QuestionTemplate。
If you want to create a collection of similar classes I advise you to read about polymorphism :) 如果您想创建类似类的集合,建议您阅读有关多态的信息:)
Example 例
Like @ luk2302 said you should create class QuestionTemplate and then implement two classes. 就像@ luk2302所说的那样,您应该创建类QuestionTemplate,然后实现两个类。
first: 第一:
QuestionTemplateA extends QuestionTemplate QuestionTemplateA扩展了QuestionTemplate
second: 第二:
QuestionTemplateB extends QuestionTemplate QuestionTemplateB扩展了QuestionTemplate
and you can create new collections of QuestionTemplate where you can put both classes 然后您可以创建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.