我有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。

09-13 10:43