0 votes
1 view
in Java by (1.1k points)
edited by

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<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");
        }
    };
}

1 Answer

0 votes
by (72.2k points)

The instance initialiser is just to make things easier in this case. I don't see the need for an extra anonymous class just to initialize. And it won't work if the class being created is final.

Here is how 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);

    }

}

If you want to learn Java, I recommend this Java Training by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Aug 13, 2019 in Java by Nigam (4.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...