Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a String to an array of ints - Java

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.

like image 501
jbreed Avatar asked Jan 26 '26 22:01

jbreed


2 Answers

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

map.put("foo", new int[]{5, 1, 3, 2});
like image 119
Jeremy Avatar answered Jan 29 '26 10:01

Jeremy


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});
}
like image 37
Bala R Avatar answered Jan 29 '26 10:01

Bala R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!