简体   繁体   English

使用不同的泛型类型参数映射值

[英]Map with values using different generic type parameters

I am trying to do something like the following: 我正在尝试执行以下操作:

  private static final ImmutableMap<String, List<?>> lists = ImmutableMap.of(
      "A", new ArrayList<String>(),
      "B", new ArrayList<Integer>());

Essentially, the primary distinction I am trying to capture is that the different values have different type parameters. 本质上,我试图捕获的主要区别是不同的值具有不同的类型参数。 However this gives the error: 但这给出了错误:

Type mismatch: cannot convert from 
ImmutableMap<String,ArrayList<? extends Object&Serializable&Comparable<?>>>
to ImmutableMap<String,List<?>>

Is there a better way to do this or some way around this problem? 是否有更好的方法可以解决此问题?

Your code compiles fine in Java 1.8, but it fails to compile in Java 1.7. 您的代码在Java 1.8中可以正常编译,但在Java 1.7中无法编译。 Included in Java 1.8 is improved target type inference . Java 1.8中包括改进的目标类型推断

Basically what this means is that in Java 1.7, the compiler will infer the most specific type of a generic type parameter possible, even if that will cause a compiler error with the target type (in this case, ImmutableMap<String, List<?>> ). 基本上,这意味着在Java 1.7中,编译器将推断出通用类型参数的最具体类型,即使这会导致目标类型出现编译器错误(在这种情况下, ImmutableMap<String, List<?>> )。

In Java 1.8, the target type is taken into account, such that the type parameter of the map's value is taken to be List<?> instead of ArrayList<? extends Object&Serializable&Comparable<?>> 在Java 1.8中,考虑了目标类型,因此映射值的type参数被视为List<?>而不是ArrayList<? extends Object&Serializable&Comparable<?>> ArrayList<? extends Object&Serializable&Comparable<?>> . ArrayList<? extends Object&Serializable&Comparable<?>>

You can either upgrade to Java 1.8, or you can supply an explicit type parameter to the call to the of method . 你可以升级到Java 1.8,或者你可以提供一个明确的类型参数调用of方法

private static final ImmutableMap<String, List<?>> lists =
     //           vvvvvvvvvvvvvvvvv
     ImmutableMap.<String, List<?>>of(
          "A", new ArrayList<String>(),
          "B", new ArrayList<Integer>());

Your code should work, but this is the general concept that I believe you want: 您的代码应该可以工作,但这是我相信您想要的一般概念:

private ImmutableMap<String, List<T extends Object&Serializable&Configurable<?>>> = ...;

You can't do it with wildcards, but can with named types. 您不能使用通配符,但是可以使用命名类型。 So you may need to declare the type at class level instead of field level, but then you can use your declared type in the normal manner. 因此,您可能需要在类级别而不是字段级别声明类型,但是您可以按常规方式使用声明的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM