Java Code Trick: Double Brace Initialization [Snippet]
Java Code Trick: Double Brace Initialization [Snippet]
Want to know how to initialize a collection in Java while saving time adding elements to it? See how two sets of braces can help you out.
Join the DZone community and get the full member experience.
Join For FreeDownload Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.
While coding for our current project, I had the following thought: "Is it possible somehow not to write the variable of the collection every time I want to add some elements to it?" So I searched if there is a way to do that and found out a solution that I assume is a code trick in Java. It is not very intuitive, but it was quite easy to use. Below, I will first share the standard initialization we do and then the code trick to show you how it improves the process.
Standard Initialization of a Collection in Java
Usually, we initialize a set this way:
Now you can see how long a name we have for this set, but this is recommended for quality conventions and a better understanding of the code. In this code snippet, we have written the variable name of the set four times just to add elements to it.
Also, you may want to initialize set as a constant:
And here we have the same – writing the constant set name before adding an element to it.
Code Trick With Double Brace Initialization
Yes, we can create and initialize a new collection as an expression by using the “double-brace” syntax:
As you can see, you are able to add elements to the collection on initialization just by using add, without writing the variable name of the collection. I find it very useful when you want to add elements to a collection at the initialization step.
Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat.
Published at DZone with permission of Ilyian Kiryakov , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}