Home How can I initialise a static Map?
Reply: 0

How can I initialise a static Map?

user734
1#
user734 Published in July 23, 2018, 1:34 pm

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 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");
        }
    };
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.587704 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO