Java 如何使用List调用方法<;儿童>;,但是方法';s参数是List<;家长>;?

Java 如何使用List调用方法<;儿童>;,但是方法';s参数是List<;家长>;?,java,inheritance,parent,extends,Java,Inheritance,Parent,Extends,我有一些问题,我不明白为什么它不起作用。 我有一个父类: public abstract class Parent { ... } 和2个儿童班: public class Child1 extends Parent { ... } public class Child2 extends Parent { ... } 我有一个方法,就是处理儿童列表。但它应该适用于Child1和Child2类型,所以我认为它应该适用: public static void doSom

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

public abstract class Parent {
    ...
}
和2个儿童班:

public class Child1 extends Parent {
    ...
}

public class Child2 extends Parent {
    ...
}
我有一个方法,就是处理儿童列表。但它应该适用于Child1和Child2类型,所以我认为它应该适用:

public static void doSomething(List<Parent> list) {
    ...
}
public静态无效doSomething(列表){
...
}
我这样称呼它:

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

List<Child2> children2 = dao.getChildren("2");
doSomething(children2);
List children=dao.getChildren(“1”);
doSomething(儿童);
List children2=dao.getChildren(“2”);
doSomething(儿童2);
但它不起作用,它显示了以下错误:

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>)
MyClass类型中的方法doSomething(列表)不适用于参数(列表) MyClass类型中的方法doSomething(列表)不适用于参数(列表)
我怎么能写这段代码呢?

哦,我做到了!此代码适用于剂量测定法:

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

publicstaticvoiddosomething(ListOh我做到了!此代码适用于doSomething方法:

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

public static void doSomething(listDosomething()返回什么?你的代码没有显示返回类型我更新了,很抱歉,但这并不重要。我读这个问题太快了,以为你在做List children=doSomething(children)。事后看来有点傻:)doSomething()是什么return?您的代码没有显示返回类型我更新了,很抱歉,但这与该方法的作用无关。我看问题太快了,以为您在做List children=doSomething(children)。事后看来有点傻:)