问题
I need to initialize an ImmutableMap (guava 21.0) and I need it to resolve to a Map> for this example I will just use String.
So I have:
import com.google.common.collect.ImmutableMap;
public class MyClass {
private Map<String,String> testMap =
ImmutableMap<String,String>.builder().put("a","b").build();
and on that last line I get a huge amount of compiler errors. The use of ImmutableMap<String,String>.of()
gets the same result.
If I remove I just get one error, a type mismatch.
How can I use ImmutableMap for explicit (literal-like) initialization when I do want a map with explicit types?
回答1:
Place generic types after the dot:
private Map<String, String> testMap =
ImmutableMap.<String, String>builder().put("a","b").build();
See great Angelika Langer's Generics FAQ section on "What is explicit type argument specification?" for more details.
回答2:
In case you don't need to use the builder, there's no need to specify generic type parameters either.
Just use:
Map<String, String> map = ImmutableMap.of("a", "b");
Generic type parameters will be inferred by the compiler.
If, on the other hand, you need to use the builder, then the answer from @Xaerxess explains what you have to do.
来源:https://stackoverflow.com/questions/43869399/initialize-an-immutablemap-with-explicit-types