Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I interpret this statement about Initializer in Java? [duplicate]

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

like image 774
Saurabh Gokhale Avatar asked Jun 09 '26 19:06

Saurabh Gokhale


1 Answers

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.

like image 91
Brian Agnew Avatar answered Jun 11 '26 08:06

Brian Agnew