Double Brace Initialization

  • Easiest and Most Popular way:
Set<String> validCodes = new HashSet<>();
validCodes.add("Dev");
validCodes.add("QA");
  • Double Brace Initialization:
Set<String> validCodes = new HashSet<String>() { 
   {
      add("Dev");
      add("QA");
   } 
} ==> Even This works fine.

OR

Set<String> validCodes = new HashSet<String>() {
     {
     add("Dev");
     } 
     {
     add("QA");
     } 
 } ==> Even This works fine.

Here, in above doubleBrace scenario, the outer brace creates an anonymous class of HashSet and inner brace intializes values.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.