gpt4 book ai didi

java - 抽象方法中的通用列表

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:08 25 4
gpt4 key购买 nike

我有一个像这样的基抽象类:

public abstract class BaseModel {
//some code
}

我用另一个 Base 抽象类来扩展它,如下所示:

public abstract class BaseChildParentModel extends BaseModel {

public abstract <E extends BaseModel> List<E> getChildren();

public abstract <E extends BaseModel> List<E> createChildList();

public void addChild(BaseModel child) {
List<BaseModel> children = getChildren();
if (children == null)
children = createChildList();
children.add(child);
}
}

我的最后一个类扩展BaseChildParentModel,如下所示:

public class Subject extends BaseChildParentModel {

//some fields

public ArrayList<Subject> ChildSubjects;

@Override
public <E extends BaseModel> List<E> getChildren() {
return ChildSubjects;
}

@Override
public <E extends BaseModel> List<E> createChildList() {
ChildSubjects = new ArrayList<>();
return ChildSubjects;
}
}

编译时出现以下错误:

Error:(52, 16) error: incompatible types
required: List<E>
found: ArrayList<Subject>
where E is a type-variable:
E extends BaseModel declared in method <E>getChildren()

Error:(58, 16) error: incompatible types
required: List<E>
found: ArrayList<Subject>
where E is a type-variable:
E extends BaseModel declared in method <E>createChildList()

我的错是什么?

最佳答案

试试这个:

public abstract class Subject extends BaseChildParentModel {
public List<Subject> ChildSubjects;

@Override
public <E extends BaseModel> List<E> getChildren() {
return (List<E>) ChildSubjects;
}

@Override
public <E extends BaseModel> List<E> createChildList() {
ChildSubjects = new ArrayList<>();
return (List<E>) ChildSubjects;
}
}

关于java - 抽象方法中的通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com