initializing a Guava ImmutableMap

后端 未结 3 1885
半阙折子戏
半阙折子戏 2020-12-12 12:47

Guava offers a nice shortcut for initializing a map. However I get the following compiler error (Eclipse Indigo) when my map initializes to nine entries.

The metho

相关标签:
3条回答
  • 2020-12-12 13:19

    if the map is short you can do:

    ImmutableMap.of(key, value, key2, value2); // ...up to five k-v pairs
    

    If it is longer then:

    ImmutableMap.builder()
       .put(key, value)
       .put(key2, value2)
       // ...
       .build();
    
    0 讨论(0)
  • 2020-12-12 13:23

    Notice that your error message only contains five K, V pairs, 10 arguments total. This is by design; the ImmutableMap class provides six different of() methods, accepting between zero and five key-value pairings. There is not an of(...) overload accepting a varags parameter because K and V can be different types.

    You want an ImmutableMap.Builder:

    ImmutableMap<String,String> myMap = ImmutableMap.<String, String>builder()
        .put("key1", "value1") 
        .put("key2", "value2") 
        .put("key3", "value3") 
        .put("key4", "value4") 
        .put("key5", "value5") 
        .put("key6", "value6") 
        .put("key7", "value7") 
        .put("key8", "value8") 
        .put("key9", "value9")
        .build();
    
    0 讨论(0)
  • 2020-12-12 13:28

    "put" has been deprecated, refrain from using it, use .of instead

    ImmutableMap<String, String> myMap = ImmutableMap.of(
        "city1", "Seattle",
        "city2", "Delhi"
    );
    
    0 讨论(0)
提交回复
热议问题