How can I initialise a static Map?

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

    public class Test {
        private static final Map myMap;
        static {
            Map aMap = ....;
            aMap.put(1, "one");
            aMap.put(2, "two");
            myMap = Collections.unmodifiableMap(aMap);
        }
    }
    

    If we declare more than one constant then that code will be written in static block and that is hard to maintain in future. So it is better to use anonymous class.

    public class Test {
    
        public static final Map numbers = Collections.unmodifiableMap(new HashMap(2, 1.0f){
            {
                put(1, "one");
                put(2, "two");
            }
        });
    }
    

    And it is suggested to used unmodifiableMap for constants other wise it can't be treated as constant.

提交回复
热议问题