Double Brace Initialization In Java

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)

Double Brace Initialization of the same code:

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.

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.