Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (19k points)

How to initialize a static Map in Java?

Method one: static initialiser 

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

Please tell me the benefits and disadvantages 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");

        }

    };

}

1 Answer

0 votes
by (33.1k points)

The instance initializer in java is similar to syntactic sugar. You can simply create an immutable map using a static initializer.

For example:

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

    }

}

Hope this answer helps you!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 30, 2021 in Java by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 24, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 24, 2021 in Java by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...