Standard Initialization of collection in Java
Usually we initialize a set this way:
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:
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 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.