初始化番石榴ImmutableMap [英] initializing a Guava ImmutableMap

查看:179
本文介绍了初始化番石榴ImmutableMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

番石榴为初始化地图提供了一个很好的捷径。但是当我的地图初始化为九个条目时,我会收到以下编译器错误(Eclipse Indigo)。



(K,V,K,V,K,V,K,V,K,V)的方法 ImmutableMap 不适用于参数
(String,String,String,String,String,String,String,字符串,字符串,字符串,字符串,字符串,字符串,字符串)字符串,字符串,字符串,字符串)

 $ C> ImmutableMap<字符串,字符串> myMap = ImmutableMap.of(
key1,value1,
key2,value2,
key3,value3,
key4 value4,
key5,value5,
key6,value6,
key7,value7,
key8 ,
key9,value9
);

消息似乎说


一个ImmutableMap的最大大小为四对键值。


显然,这不能是案例,但我不知道如何增加我的初始化程序的大小。



有人可以告诉我缺少什么?


请注意,您的错误消息只包含五个 K,V 对,总共有10个参数。

解决方案

这是设计; ImmutableMap类提供了()方法的六个不同的方法,接受零到六个键值配对。由于 K ,不存在(...)重载接受varags参数的

你想要一个 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
.put(key7,value7)
.put(key8,value8)
.put(key9,value9)
.build();


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 method of(K, V, K, V, K, V, K, V, K, V) in the type ImmutableMap is not applicable for the arguments (String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String)

ImmutableMap<String,String> myMap = ImmutableMap.of(
        "key1", "value1", 
        "key2", "value2", 
        "key3", "value3", 
        "key4", "value4", 
        "key5", "value5", 
        "key6", "value6", 
        "key7", "value7", 
        "key8", "value8", 
        "key9", "value9"
        );

The message appears to say that

An ImmutableMap has a maximum size of four pairs of key,value.

Obviously, this cannot be the case but I can't figure out what to do to increase the size of my initializer.

Can someone tell me what is missing?

解决方案

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 six 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();

这篇关于初始化番石榴ImmutableMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆