开发者

writing an initialized static hashtable elegantly [duplicate]

This question already has answers here: Initializing Hashtables in Java? (10 answers) 开发者_开发百科 Closed 5 years ago.

Is there a way to write a static final Hashtable in java in key value pairs just like you can initialize a string array conveniently as :

String [] foo = {"A","AB"};

Basically what I mean is not having to write the words "put" for key:value pairs but instead may be something like:

Hashtable<String, String> foo = {"JJ":"222","KK":"222"}

which IMO looks more elegant.

(I know the initialization would need to be in a static block. I am leaving that out for now)


An anonymous inner class would give you double brace initialization, which is useful in some cases:

static final Map<String, String> map = new HashMap<String, String>() {{
    put("foo", "bar");
    put("x", "y");
}};

In any case, @michael667's answer is probably the best


You can use guava's ImmutableMap:

map = ImmutableMap.of(key1, value1, key2, value2);

These convenience methods exist for one to five elements. If you need more, you can use an ImmutableMap.Builder:

static final ImmutableMap<String, Integer> WORD_TO_INT =
   new ImmutableMap.Builder<String, Integer>()
     .put("one", 1)
     .put("two", 2)
     .put("three", 3)
     .build();


No, Java doesn't have map literals, but it does have array literals.

static final Map<String, String> map;

static {
    map = new HashMap<String, String>();
    String[][] pairs = {
        {"foo", "bar"},
        {"x", "y"}
    };
    for (String[] pair : pairs) {
        map.put(pair[0], pair[1]);
    }
}

Of course this doesn't really add anything to the straightforward copy and paste put solution, and it doesn't work well if your key and value types aren't the same.


No, you're looking for something like C#'s collection initializers, which doesn't currently exist in Java.

You can use an anonymous class to save a little typing, but you still have to write put.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜