What is Double Brace initialization in Java?

sgokhales picture sgokhales · Dec 24, 2009 · Viewed 88.8k times · Source

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

Answer

Brian Agnew picture Brian Agnew · Dec 24, 2009

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<Integer>() {{
   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.