How can I initialise a static Map?

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

    I do not like Static initializer syntax and I'm not convinced to anonymous subclasses. Generally, I agree with all cons of using Static initializers and all cons of using anonymous subclasses that were mentioned in previus answers. On the other hand - pros presented in these posts are not enough for me. I prefer to use static initialization method:

    public class MyClass {
        private static final Map myMap = prepareMap();
    
        private static Map prepareMap() {
            Map hashMap = new HashMap<>();
            hashMap.put(1, "one");
            hashMap.put(2, "two");
    
            return hashMap;
        }
    }
    

提交回复
热议问题