Java Code Trick: Double Brace Initialization

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 […]

by Iliyan Kiryakov

December 19, 2017

2 min read

business 2717066 1920 - Java Code Trick: Double Brace Initialization
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.

Java EE and Oracle Developer at Dreamix