Java Code Trick: Double Brace Initialization

Java Code Trick: Double Brace Initialization

December 19, 2017
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 to it some elements?“. So I searched if there is a way to do that and found out a solution which I assume as a code trick in Java. It is not so intuitively, but is quite comfortable 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 collection in Java

Usually we initialize a set this way:

Double Brace Initialization

Now you can see how long name we have for this set, but this is recommendable for quality conventions and better understanding of the code. In this code snippet we have written 4 times the variable name of the set just for adding elements to it.

Also you may want to initialize set as a constant:

Double Brace Initialization

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:

Double Brace Initialization

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 the collection on initialization step.

Share if it was interesting and useful for you. Feel free to ask questions or give ideas related to this blog.

Iliyan Kiryakov

Java EE and Oracle Developer at Dreamix

More Posts - Website

Follow Me:

Do you want more great blogs like this?

Subscribe for Dreamix Blog now!