Double Brace Initialization in Java - GeeksforGeeks

24 Dec, 2021
The combination of two separate processes in Java is known as Double Brace Initialization in Java. As the name suggests, there are two braces {{ included in it.
A single brace { is nothing new for programmers. The first brace in the double brace initialization is used to create an anonymous inner class. We have made many anonymous inner classes in such a way. The second brace is what makes it different from the normal braces in Java. The second brace is the initialization block which is used with the declared anonymous inner class. When this initialization block is used with the anonymous inner class, it is known as Java double brace initialization.
It has fewer lines of code compared to the native way of creation and initialization.
The code is more readable.
Creation and Initialization are done in the same expression.
It is Obscure and is not a widely known way to do the initialization.
It creates an extra class every time we use it.
It doesn’t support the use of the “diamond operator” – a feature introduced in Java 7.
It doesn’t work if the class we are trying to extend is marked as final.
It holds a hidden reference to the enclosing instance, which may cause memory leaks.
Note: It’s due to these disadvantages that double brace initialization is considered as an anti-pattern.
Implementation:
Geeks, if you are unaware of double brace initialization you are already using the standard approach that is without double brace initialization for which we have proposed a sample below as follows:  
Procedure: When we use a collection in a code, we typically do the following.
Declare a variable for a temporary collection.Create a new empty collection and store a reference to it in the variable.Put things into the collection.Pass the collection to the method.
Declare a variable for a temporary collection.
Create a new empty collection and store a reference to it in the variable.
Put things into the collection.
Pass the collection to the method.
Example: Standard Approach
Java
// Java program to Demonstrate Working of Collections// Without Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG {     // Method 1    // Main driver method    public static void main(String[] args)    {        // Creating an empty HashSet of string entries        Set<String> sets = new HashSet<String>();         // Adding elements to Set        // using add() method        sets.add("one");        sets.add("two");        sets.add("three");         // Calling method 2 inside main() method        // Now pass above collection as parameter to method        useInSomeMethod(sets);    }     // Method 2    // Helper method    private static void useInSomeMethod(Set<String> sets)    {        // Print all elements of desired Set        // where method is invoked        System.out.println(sets);    }}
[one, two, three]
Output explanation:
Above are normal steps we all follow in our coding practices. Don’t you feel that Java should have a more convenient syntax for collections (lists, maps, sets, etc.)? Let’s see another easy way of doing it. This is known as double brace initialization. Java Double Brace Initialization is used to combine the creation and initialization in a single statement. Using double brace initialization, we can initialize collections.
Procedure: When we use a double brace initialization in a code, we typically do the following.
Create an anonymous inner class that extends sets.Provide an instance initialization block that invokes the add method and adds the elements to the set.Pass the set to the method.
Create an anonymous inner class that extends sets.
Provide an instance initialization block that invokes the add method and adds the elements to the set.
Pass the set to the method.
Example:
Java
// Java program to Demonstrate Working of Collections// With Double Brace Initialization // Importing required classesimport java.util.HashSet;import java.util.Set; // Main class// DoubleBracepublic class GFG {     // Main driver method    public static void main(String[] args)    {         // Creating an empty HashSet        Set<String> sets = new HashSet<String>()         // Double brace        {            {                // Adding elements to above HashSet                // This is double brace initialization                add("one");                add("two");                add("three");            }        };         // ...        // Now pass above collection as parameter to method        // Calling method 2 inside main() method        useInSomeMethod(sets);    }     // Method 2    private static void useInSomeMethod(Set<String> sets)    {         // Print elements of the desired Set        // where method is invoked        System.out.println(sets);    }}
[one, two, three]
Output Explanation: The first brace creates a new Anonymous Inner Class. These inner classes are capable of accessing the behavior of their parent class. So, in our case, we are creating a subclass of the HashSet class so that this inner class can use the add() method. The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created. 
This article is contributed by Saumya Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
solankimayank
Java-Collections
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashtable in Java
Constructors in Java
Different ways of Reading a text file in Java
Comparator Interface in Java with Examples
Java Math random() method with Examples
HashMap containsKey() Method in Java
How to Create Array of Objects in Java?
Convert Double to Integer in Java
Iterating over ArrayLists in Java
Generating random numbers in Java