How can I initialise a static Map?

前端 未结 30 1571
慢半拍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:34

    I would use:

    public class Test {
        private static final Map MY_MAP = createMap();
    
        private static Map createMap() {
            Map result = new HashMap<>();
            result.put(1, "one");
            result.put(2, "two");
            return Collections.unmodifiableMap(result);
        }
    }
    
    1. it avoids an anonymous class, which I personally consider to be a bad style, and avoid
    2. it makes the creation of map more explicit
    3. it makes map unmodifiable
    4. as MY_MAP is constant, I would name it like constant

提交回复
热议问题