84

Java Code Trick: Double Brace Initialization [Snippet] - DZone Java

 6 years ago
source link: https://dzone.com/articles/java-code-trick-double-brace-initialization
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:

Double Brace Initialization

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:

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK