How to create a static Map of String -> Array

后端 未结 6 757
我寻月下人不归
我寻月下人不归 2021-01-11 10:51

I need to create a static Map which maps a given String to an array of int\'s.

In other words, I\'d like to define something l

6条回答
  •  春和景丽
    2021-01-11 11:21

    You don't need to separate declaration and initialization. If you know how, it can all be done in one line!

    // assumes your code declaring the constants ONE, FRED_TEXT etc is before this line
    private static final Map myMap = Collections.unmodifiableMap(
        new HashMap() {{
            put(FRED_TEXT, new int[] {ONE, TWO, FOUR});
            put(DAVE_TEXT, new int[] {TWO, THREE});
        }});
    

    What we have here is an anonymous class with an initialization block, which is a block of code that executes on construction after constructor, which we've used here to load the map.

    This syntax/construct is sometimes erroneously called "double brace initialization" - I suppose because there's two adjacent braces - but there's actually no such thing.

    The two cool things about this are:

    • it marries the declaration with the contents, and
    • because the initialization is in-line, you can also make an in-line call to Collections.unmodifiableMap(), resulting in a neat one-line declaration, initialization and conversion to unmodifiable.

    If you don't need/want the map to be unmodifiable, leave out that call:

    private static final Map myMap = new HashMap() {{
        put(FRED_TEXT, new int[] {ONE, TWO, FOUR});
        put(DAVE_TEXT, new int[] {TWO, THREE});
    }};
    

提交回复
热议问题