2

How do I map a String to a statically defined array of ints? I tried

private static Map<String, int[]> map = new HashMap<String, int[]>();
static {
    map.put("foo", {5, 1, 3, 2});
    map.put("bar", {2, 7, 8});
}

which tells me that {5, 1, 3, 2} is illegal.

3 Answers 3

9

You need to call the array's constructor before you initialize the content.

map.put("foo", new int[]{5, 1, 3, 2});
Sign up to request clarification or add additional context in comments.

Comments

5

Try

private static Map<String, int[]> map = new HashMap<String, int[]>();
static {
    map.put("foo", new int[]{5, 1, 3, 2});
    map.put("bar", new int[]{2, 7, 8});
}

Comments

0

If the map will never be changed, you could use Guava lib:

private static ImmutableMap<String, int[]> immutaleMap =
    ImmutableMap.of("foo", new int[]{5, 1, 3, 2},
                    "bar", new int[]{2, 7, 8}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.