Double Brace Initialization

Java does not have an easy one-line syntax to create and initialize collections (list, maps, sets, etc).
In order to create a simple initialized collection you have to:
  1. Declare a variable for a temporary collection
  2. Create a new empty collection and store a reference to it in the variable
  3. Put things into the collection
  4. Pass the collection to the method
For example:

List people = new ArrayList();
Person a = new Person();
Person b = new Person();

then pass it to some function e.g. printList(people);
Boring isn’t it?
A JAVA trick is here to overcome this situation called the {{ Double Brace Initialization }}
Consider the same example as above but using the Double Brace Initialization:
List people = new ArrayList(){{
     add(new Person(){{
     add(new Person(){{
Faster and cleaner!
What is happening actually is that we are creating an anonymous inner class of the original class and instantiating it using instance initializer block.
The drawback of this method is that it needs more time and space to create and initialize the object.
This is negligible for small uses but you should be careful not scatter them all around your code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s