“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.
The output is given below,
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.
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.