首页 > 解决方案 > 为什么我不能设置来自不同包中类似类的对象列表

问题描述

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

现在做什么?

标签: javalistcopy

解决方案


例如,您必须从包 B 中删除 QuestionList 和 QuestionTemplate,然后在 B 类中,您必须从包 A 中导入 QuestionList 和 QuestionTemplate。


推荐阅读