How can I initialise a static Map?

前端 未结 30 1014
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  不思量自难忘°
    2020-11-22 09:29

    I would never create an anonymous subclass in this situation. Static initializers work equally well, if you would like to make the map unmodifiable for example:

    private static final Map MY_MAP;
    static
    {
        MaptempMap = new HashMap();
        tempMap.put(1, "one");
        tempMap.put(2, "two");
        MY_MAP = Collections.unmodifiableMap(tempMap);
    }
    

提交回复
热议问题