Double brace initialization in java







As the name suggest this (hidden or not so famous) feature allows initialization in java in short cut way. Now lets look how double brace initialization works.

Lets first consider the normal initialization way , suppose we are initializing the ArrayList we do something like following :
List fruits = new ArrayList();
fruits.add( "apple" );
fruits.add( "mango" );
fruits.add( "citrus" );


But using the double brace initialization technique we can initialize it in one line as follows :

List fruits = new ArrayList(){{ add( "apple" ); add( "mango" ); add( "citrus" ); }};


Now lets see what these two braces do. First brace is basically creates the Anonymous inner class and the second brace works for initializing the instance of an object. These initializer blocks should always run before the constructor.

Now lets look at the following code snippet for example :

        List shapes = new ArrayList(){{ add( "circle" ); add( "rectangle" ); add( "square" ); }};

        for( int i = 0 ; i < shapes.size() ; i++ ){
            System.out.println( shapes.get(i));
        }
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment