简体   繁体   中英

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. 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.

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. Then call B class set method and send in the ListCopy just created from A class.

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.

  • first:

    QuestionTemplateA extends QuestionTemplate

  • second:

    QuestionTemplateB extends QuestionTemplate

and you can create new collections of QuestionTemplate where you can put both classes

List<QuestionTemplate> list = new ArrayList<>();
QuestionTemplateA a = new QuestionTemplateA();
QuestionTemplateB b = new QuestionTemplateB();
list.add(a);
list.add(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM