Initialize an ImmutableMap with explicit types?

﹥>﹥吖頭↗ 提交于 2019-12-24 01:32:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!