Friday, April 15, 2011

Double Brace Initialization in Java!

Few days back I came to know about a different way of initializing collections and objects in Java. Although this method of initialization has been there in Java since quite a few years now, very few people actually knows about it or have used it in their code. The technique is called Double Brace Initialization technique in Java.
Let us see first how we will initialize an ArrayList in Java by “normal” way:

List<String> countries = new ArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");

Above code snippet first creates an object of ArrayList type String and then add one by one countries in it.

Now check the Double Brace Initialization of the same code:
List<String> countries = new ArrayList<String>() {{
    add("India");
    add("Switzerland");
    add("Italy");
    add("France");
    add("Germany");
}};

How does this works?

Well, the double brace ( {{ .. }} ) initialization in Java works this way. The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an “instance initializer”, because it is declared withing the instance scope of the class — “static initializers” are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class . The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.
If you have not understood the concept, try executing following code and it will make things clear for you.


public class Test {
    public Test() {
        System.out.println("Constructor called");
    }
    static {
        System.out.println("Static block called");
    }
 
    {
        System.out.println("Instance initializer called");
    }
 
    public static void main(String[] args) {
        new Test();
        new Test();
    }
}

Output:

Static block called
Instance initializer called
Constructor called
Instance initializer called
Constructor called
Thus the instance initializer code will be called each time a new instance of object is created.

No comments:

Post a Comment

Chitika