Double Brace Initialization in Java
When we use a collection in your 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.
For example:
filter_none
edit
play_arrow
brightness_4
|
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 known as double brace initialization.
filter_none
edit
play_arrow
brightness_4
|
Output:
[one, two, three]
How does the 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 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
post a comment