在Java中混合嵌套类型参数和通配符 [英] Mixing nested type parameters and wildcards in Java

查看:317
本文介绍了在Java中混合嵌套类型参数和通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要编译

  public class GenericsFail {
public static void main(String [] args) {
accept(new HashMap< String,List< String>>());

$ b public static void accept(Map< String,List<>> multiMap){}
}

给出错误

  GenericsFail.java:7:错误:类GenericsFail中的方法接受不能应用于给定的类型; 
accept(new HashMap< String,List< String>>());
^
required:Map< String,List<>>找到
:HashMap< String,List< String>>
reason:实际参数HashMap< String,List< String>>不能转换成Map< String,List<>>>通过方法调用转换

通配符只有在嵌套在 List 。

解决方案

更普遍

< pre $ void accept(Map< String,?extends List<>> multiMap)


Why does trying to compile

public class GenericsFail {
    public static void main(String[] args) {
        accept(new HashMap<String, List<String>>());
    }

    public static void accept(Map<String, List<?>> multiMap) {}
}

give the error

GenericsFail.java:7: error: method accept in class GenericsFail cannot be applied to given types;
                accept(new HashMap<String, List<String>>());
                ^
  required: Map<String,List<?>>
  found: HashMap<String,List<String>>
  reason: actual argument HashMap<String,List<String>> cannot be converted to Map<String,List<?>> by method invocation conversion

The wildcard is only allowed if it's not nested inside List.

解决方案

To be more general

void accept(Map<String, ? extends List<?>> multiMap)

这篇关于在Java中混合嵌套类型参数和通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆