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();
a.setName(“ali”);
a.setAge(25);
Person b = new Person();
b.setName(“p2”);
b.setAge(26);
people.add(a);
people.add(b);

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(){{
          setName(“ali”);
          setAge(25);
     }});
     add(new Person(){{
          setName(“ali”);
          setAge(25);
     }});
}};
printList(people);
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.
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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