Static Initialization Blocks

前端 未结 14 1265
暗喜
暗喜 2020-11-22 01:56

As far as I understood the \"static initialization block\" is used to set values of static field if it cannot be done in one line.

But I do not understand why we ne

14条回答
  •  梦如初夏
    2020-11-22 02:38

    I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.

    To re-use some examples posted here.

    This piece of code could be re-written without using static initialiser.

    Method #1: With static

    private static final HashMap MAP;
    static {
        MAP.put("banana", "honey");
        MAP.put("peanut butter", "jelly");
        MAP.put("rice", "beans");
      }
    

    Method #2: Without static

    private static final HashMap MAP = getMap();
    private static HashMap getMap()
    {
        HashMap ret = new HashMap<>();
        ret.put("banana", "honey");
        ret.put("peanut butter", "jelly");
        ret.put("rice", "beans");
        return ret;
    }
    

提交回复
热议问题