Java: Double brace initialization

“Double Brace Initialization” is a hidden feature of Java and used for initializing collection classes such as ArrayList, HashSet, and HashMap.

Even though the code looks more readable with this feature, be aware that it can cause memory issues.

In this post, we are going to see how we can use this with an example.

DoubleBraceInit

The output is given below,

{1=data1, 2=data2}

In the above code, dataMap is a HashMap which contains a key/value and double brace block contains the code to initialize this HashMap.

When a code contains a double brace block, then the compiler would generate an anonymous inner class which extends that collection class.

Let’s verify this with the above example. After compilation, I checked the target folder and it contains the below class files.

DoubleBraceInit-class

I opened up the DoubleBraceInitTester$1.class which is an anonymous inner class and it looks like below. So the compiler copied all the initialization code into the constructor of this class.

DoubleBraceInit-decompiler

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s