如何使用List调用方法<Child>,但方法的参数是List<Parent>?



我有一些问题,我不明白为什么它不起作用。我有父母课程:

public abstract class Parent {
    ...
}

和2个儿童课:

public class Child1 extends Parent {
    ...
}
public class Child2 extends Parent {
    ...
}

我有一种方法,该方法正在与儿童列表合作。但是它应该与Child1和Child 2的类型一起使用,所以我认为它应该起作用:

public static void doSomething(List<Parent> list) {
    ...
}

这就是我的称呼:

List<Child1> children = dao.getChildren("1");
doSomething(children);
List<Child2> children2 = dao.getChildren("2");
doSomething(children2);

但是它不起作用,它显示了此错误:

The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child1>)
The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child2>)

如何编写此代码?

哦,我做到了!此代码适用于滴定方法:

public static void doSomething(List<? extends Parent> list) {
    ...
}

相关内容

最新更新