Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
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 (119k 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 Online Course 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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...