How to Initialise a static Map in Java

Posted by fahdshariff on Stack Overflow See other posts from Stack Overflow or by fahdshariff
Published on 2009-02-03T15:41:33Z Indexed on 2010/06/03 8:24 UTC
Read the original article Hit count: 240

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about initialization