Double Brace Initialization In Java

Another way of initializing collections and objects in Java. This is rarely known concept of Java,although this type of initialization has been with java from many years.

The technique/concept is called Double Brace Initialization technique in Java.

Lets start with an example.
Using ArrayList in java (Normal way)

List languages = new ArrayList();
languages.add("English");
languages.add("Hindi");
languages.add("German");

Double Brace Initialization of the same code:

List languages = new ArrayList() {{
    add("English");
    add("Hindi");
    add("German");
}};

Lets understand how it works
The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block, which is executed when the anonymous inner class is instantiated. If you remind the core Java Concept these two will not be new to you. Still confused see the below example.

public class InstanceTest {   
    {
        System.out.println("Instance initializer called");
    }     
}

Now if you don’t have a class name it will become as Anonymous Class ( and you understand Inner class).
Hope you are now able to catch the underlying concept.
Note : There may be some performance hit by using Double Brace Initialization in java. Check the specification before using.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.