用显式类型初始化ImmutableMap吗? [英] Initialize an ImmutableMap with explicit types?
问题描述
我需要初始化一个ImmutableMap(guava 21.0),并且需要将其解析为Map>对于本示例,我将只使用String.
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.
所以我有
import com.google.common.collect.ImmutableMap;
public class MyClass {
private Map<String,String> testMap =
ImmutableMap<String,String>.builder().put("a","b").build();
最后一行,我得到了大量的编译器错误.使用ImmutableMap<String,String>.of()
可获得相同的结果.
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.
当我确实想要具有显式类型的地图时,如何使用ImmutableMap进行显式(类似文字的)初始化?
How can I use ImmutableMap for explicit (literal-like) initialization when I do want a map with explicit types?
推荐答案
将通用类型放在之后的点上:
Place generic types after the dot:
private Map<String, String> testMap =
ImmutableMap.<String, String>builder().put("a","b").build();
查看出色的 Angelika Langer的泛型常见问题"部分中的什么是显式类型参数规范?" .
这篇关于用显式类型初始化ImmutableMap吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!