Double Brace Initialization
Probably a lot of time you whish to initialize a collection in Java with default values at construction time, but without doing the sequence stuff like this one (too many statements):
1 2 3 4 5 6 7 8 |
<span class="rem">// Initialize a cars collection</span> List<String> cars = <span class="kwrd">new</span> ArrayList<>(); cars.add(<span class="str">"Volvo"</span>); cars.add(<span class="str">"BMW"</span>); cars.add(<span class="str">"Ferrari"</span>); <span class="rem">// call the method</span> someMethod(cars); |
How to do it?
Using a static method asList (probably you know about this one!)
Functional style, fewer lines, very precise, and clear!
1 2 3 4 5 |
<span class="rem">// Initialize the collection (fewer statements!)</span> List<String> cars = <span class="kwrd">new</span> ArrayList<>(Arrays.asList(<span class="str">"Volvo"</span>, <span class="str">"BMW"</span>, <span class="str">"Ferrari"</span>)); <span class="rem">// call the method</span> someMethod(cars); |
Using Double Brace Initialization
If you think a little about it you will see nothing knew, but may surprise you this way of initialization!
1 2 3 4 5 6 7 8 9 |
<span class="rem">// Initialize the collection</span> List<String> cars = <span class="kwrd">new</span> ArrayList<String>(){{ add(<span class="str">"Volvo"</span>); add(<span class="str">"BMW"</span>); add(<span class="str">"Ferrari"</span>); }}; <span class="rem">// Call the method</span> someMethod(cars); |
Is this a hidden feature in Java? No!
If you know something about anonymous classes and anonymous constructors, nothing here is new!
The first “{“ is creating an anonymous subclass of ArrayList, and the second “{“ is used to create an anonymous constructor.
Let me put the code in another way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<span class="rem">// The collection creation!</span> <a href="http://blog.josedacruz.com/wp-content/uploads/2013/05/trick.png"><img style="background-image: none; float: right; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;" title="trick" src="http://blog.josedacruz.com/wp-content/uploads/2013/05/trick_thumb.png" alt="trick" width="244" height="244" align="right" border="0" /></a>List<String> cars = <span class="kwrd">new</span> ArrayList<String>() <span class="rem">// The anonymous subclass </span> { <span class="rem">// The anonymous constructor</span> { add(<span class="str">"Volvo"</span>); add(<span class="str">"BMW"</span>); add(<span class="str">"Ferrari"</span>); } }; <span class="rem">// The method call</span> someMethod(cars); |
More clear now?
Java has some hidden gems that they deserve to be found!