Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaDouble Brace Initialization in Java

Double Brace Initialization in Java

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.

Advantages of 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.

Disadvantages of Double Brace Initialization

  • 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.

  1. Declare a variable for a temporary collection.
  2. Create a new empty collection and store a reference to it in the variable.
  3. Put things into the collection.
  4. Pass the collection to the method.

Example: Standard Approach

Java




// Java program to Demonstrate Working of Collections
// Without Double Brace Initialization
  
// Importing required classes
import java.util.HashSet;
import java.util.Set;
  
// Main class
// DoubleBrace
public 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);
    }
}


Output

[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.

Usage of Double Brace Initialization 

Procedure: When we use a double brace initialization in a code, we typically do the following.

  1. Create an anonymous inner class that extends sets.
  2. Provide an instance initialization block that invokes the add method and adds the elements to the set.
  3. Pass the set to the method.

Example:

Java




// Java program to Demonstrate Working of Collections
// With Double Brace Initialization
  
// Importing required classes
import java.util.HashSet;
import java.util.Set;
  
// Main class
// DoubleBrace
public 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);
    }
}


Output

[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 bySaumya Mishra. If you like Lazyroar 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 Lazyroar 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.

RELATED ARTICLES

Most Popular

Recent Comments