What is Double Brace initialization in Java?

前端 未结 13 2255
旧时难觅i
旧时难觅i 2020-11-21 07:22

What is Double Brace initialization syntax ({{ ... }}) in Java?

13条回答
  •  渐次进展
    2020-11-21 07:43

    Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.

    new ArrayList() {{
       add(1);
       add(2);
    }};
    

    Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.

提交回复
热议问题