在Java泛型参数中使用父类

在Java泛型参数中使用父类,java,generics,Java,Generics,我不明白Java中的泛型是如何完全工作的。我有类似的情况,我在下面的代码中进行了简化: public static void main(String[] args) { Map<String, Collection<B>> map1 = test(); Map<String, List<B>> map2 = test(); Map<String, ArrayList<B>> map3 = test()

我不明白Java中的泛型是如何完全工作的。我有类似的情况,我在下面的代码中进行了简化:

public static void main(String[] args) {
    Map<String, Collection<B>> map1 = test();
    Map<String, List<B>> map2 = test();
    Map<String, ArrayList<B>> map3 = test();
} 

private static Map<String, ArrayList<B>> test() {
    return null;
}
publicstaticvoidmain(字符串[]args){
Map map1=test();
Map map2=test();
Map map3=test();
} 
私有静态映射测试(){
返回null;
}
创建map1或map2时,我收到一个错误,该错误表示类型不兼容-它应为ArrayList,但得到的是Collection/List


如何解决此问题?

以下是将成功编译的代码:

public static <B> void main(String[] args) {
    Map<String, ? extends Collection<B>> map1 = test();
    Map<String, ? extends List<B>> map2 = test();
    Map<String, ArrayList<B>> map3 = test();
}

private static <B> Map<String, ArrayList<B>> test() {
    return null;
}
publicstaticvoidmain(字符串[]args){
Map map1=test();
Map map2=test();
Map map3=test();
}
私有静态映射测试(){
返回null;
}
您需要添加
?扩展集合
?扩展列表
,因为写入
?扩展集合
意味着构成
映射
值的
对象
集合
类的
子类型
,因此将调用
测试()
,因为它还返回一个
映射
,其
数组列表
类型,它实际上是
集合的
子类型

还要注意,您需要在
main
test()的签名中添加


希望有帮助

以下是将成功编译的代码:

public static <B> void main(String[] args) {
    Map<String, ? extends Collection<B>> map1 = test();
    Map<String, ? extends List<B>> map2 = test();
    Map<String, ArrayList<B>> map3 = test();
}

private static <B> Map<String, ArrayList<B>> test() {
    return null;
}
publicstaticvoidmain(字符串[]args){
Map map1=test();
Map map2=test();
Map map3=test();
}
私有静态映射测试(){
返回null;
}
您需要添加
?扩展集合
?扩展列表
,因为写入
?扩展集合
意味着构成
映射
值的
对象
集合
类的
子类型
,因此将调用
测试()
,因为它还返回一个
映射
,其
数组列表
类型,它实际上是
集合的
子类型

还要注意,您需要在
main
test()的签名中添加


希望有帮助

您可能想查看以前关于此问题的问题:。您可能想查看以前关于此问题的问题:。