Support Forums

Full Version: Double Brace Initialization
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey. Consider an ArrayList as follows,

Code:
List<String> countries = new ArrayList<String>();  

countries.add("Switzerland");  

countries.add("France");  

countries.add("Germany");  

countries.add("Italy");  

countries.add("India");

You must add the variable countries before the add() method to add the strings to the arraylist. But with Double Brace Initialization, its the same code, but parly modified,

Code:
List<String> countries = new ArrayList<String>() {{  

    add("India");  

    add("Switzerland");  

    add("Italy");  

    add("France");  

    add("Germany");  

}};

As you can see, theres no longer a need to put the variable before the add() method.

Also, take a look at this class,

Code:
import java.util.*;



public class DoubleBrace {



    public DoubleBrace() {

        System.out.println("" + countries + "");

    }



    {

        System.out.println("Instance Initializer");

    }



    List<String> countries = new ArrayList<String>() {{  

        add("India");  

        add("Switzerland");  

        add("Italy");  

        add("France");  

        add("Germany");  

    }};



    public static void main(String[] argv) {

        new DoubleBrace();

    }



}

The compiler prints out the following lines,

Quote:Instance Initializer

[India, Switzerland, Italy, France, Germany]

Press any key to continue . . .

So it looks like it worked! rofl.

Im sure you can find more ways to use Double Brace Initialization. I found this pretty interesting myself.



You may also be interested in how this works,

Author Wrote: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.

Double bracing is pretty cool to know, but the downside of it is that it creates an annonymous inner class, which is more to execute than it is just to add them dynamically. So therefore, doing it this way would be slightly slower than doing it the usual way. Again, not as efficient, but a little cool to know huh? Smile