Double Brace Initialization in Java

When we use a collection in your code, we typically do 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.

For example:

// Java program to demonstrate working of Collections
// without double brace initialization.
import java.util.HashSet;
import java.util.Set;

public class DoubleBrace
{
    public static void main(String[] args)
    {
        Set<String> sets = new HashSet<String>();
        sets.add("one");
        sets.add("two");
        sets.add("three");

        // ...

        // Now pass above collection as parameter to method
        useInSomeMethod(sets);
    }

    private static void useInSomeMethod(Set<String> sets)
    {
        System.out.println(sets);
    }
}

Output:

[one, two, three]

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 know as double brace initialization .



// Java program to demonstrate working of Double
// Brace Initialization
import java.util.HashSet;
import java.util.Set;

public class DoubleBrace
{
    public static void main(String[] args)
    {
        Set<String> sets = new HashSet<String>()
        {
            {
                add("one");
                add("two");
                add("three");
            }
        };

        // ...

        // Now pass above collection as parameter to method
        useInSomeMethod(sets);
    }

    private static void useInSomeMethod(Set<String> sets)
    {
        System.out.println(sets);
    }
}

Output:

[one, two, three]

How does above code work?
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 actually creating a subclass of HashSet class, so this inner class is capable of using add() method.

The second braces are instance initializers. The code an instance initializers inside is executed whenever an instance is created.

References :
http://wiki.c2.com/?DoubleBraceInitialization

This article is contributed by Saumya Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.




Recommended Posts:



3.1 Average Difficulty : 3.1/5.0
Based on 11 vote(s)