How can I initialise a static Map?

How would you initialise a static Map in Java?

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

What are the pros and cons of each?

Here is an example illustrating the two methods:

import java.util.HashMap;
import java.util.Map;

public class Test {
    private static final Map<Integer, String> myMap = new HashMap<>();
    static {
        myMap.put(1, "one");
        myMap.put(2, "two");
    }

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

4
43

Leave a Comment