简体   繁体   中英

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. Included in Java 1.8 is improved target type inference .

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<?>> ).

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<?>> 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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