Home > DeveloperSection > Forums > How to Initialize a static Map?
Glen Martin
Glen Martin

Total Post:27

Points:191
Posted on    July-03-2015 1:17 AM

 Java Java  Collection 
Ratings:


 1 Reply(s)
 445  View(s)
Rate this:
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");
        }
    };
}


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    July-03-2015 8:35 AM

The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.

You can create an immutable map using a static initialiser too:
public class Test {
    private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        myMap = Collections.unmodifiableMap(aMap);
    }
}

Don't want to miss updates? Please click the below button!

Follow MindStick