Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Double Brace initialization in Java?

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

like image 807
Saurabh Gokhale Avatar asked Dec 24 '09 15:12

Saurabh Gokhale


People also ask

What is double brace initialization?

Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization. Java Double Brace Initialization. First brace is creation of an anonymous inner class.

What is {} used for in Java?

For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


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 130
Brian Agnew Avatar answered Sep 28 '22 07:09

Brian Agnew