2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How can I Initialize a static Map?

How would you initialise a static Map in Java?

Method one: Static initializer 
Method two: instance initialiser (anonymous subclass) or some other method?

What are the pros and cons of each?

Here is an example illustrating two methods:

import java.util.HashMap;

import java.util.Map;


public class Test {

private static final Map<Integer, String> myMap = new HashMap<Integer, String>();

static {

myMap.put(1, "one");

myMap.put(2, "two");

}


private static final Map<Integer, String> myMap2 = new HashMap<Integer, String>() {

{

put(1, "one");

put(2, "two");

}

};

}

userimage
There is One advantage to the second method is that you can wrap it with Collections.unmodifiableMap() to guarantee that nothing is going to update the collection later:

private static final Map<Integer, String> CONSTANT_MAP =
    Collections.unmodifiableMap(new HashMap<Integer, String>() {{
        put(1, "one");
        put(2, "two");
    }});

 // later on...

 CONSTANT_MAP.put(3, "three"); // going to throw an exception!

Answer is