navigation

Java Code Trick: Double Brace Initialization

Java Code Trick: Double Brace Initialization

by
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:
TwitterLinkedIn

Do you want more great blogs like this?

Subscribe for Dreamix Blog now!

  • Hi Iliyan,
    the last approach has some downsides that might be worth mentioning (e.g. hidden references).
    There is another nice write-up regarding these issues here: http://www.jesperdj.com/2016/07/19/dont-use-the-double-brace-initialization-trick/
    Thanks to JEP-269 (http://openjdk.java.net/jeps/269) things are better now in Java 9 and we’re able to initialize a set like this .. Set names = Set.of(“foo”, “bar”, “baz”);

    • Iliyan Kiryakov

      Hi Micha,

      Thank you for the answer. I understood something new about the topic and I totally agree with you after reading the write-up that you referred to. For sure in Java 9 is much better such initialization. I didn’t go to use it more deeply, because I just understood for it before a month. Currently I am using brace initialization only in unit tests when I am mocking objects, without threads and etc. We are not using Java 9 already and in this case I find it useful. Anyway Sonar build is also complaining for this code with minor priority. I think this can remain just as a code trick which you can ask or be asked on interview for a job :)