Java double brace initialization explained by example

Double brace initialization in Java

The ability to quickly initialize contents of a List or Set has always been a capability Java developers have longed for.

Which is why it’s strange that so many developers are unaware of Java’s relatively new double brace initialization feature.

Historically, when seeding list data for tests or assertions, Java developer would need to follow a verbose pattern that looks something like this:

ArrayList<String> list = new ArrayList<String>();
list.add("alpha");
list.add("beta");
list.add("charlie");
list.add("devo");

Double brace initialization brings a slightly simpler approach to the Java ecosystem.

How to do double brace initialization in Java

The goal of Java’s double brace initialization feature is to reduce some of the verbosity of boilerplate Java code.

To use the Java double brace initialization feature, just follow these steps:

  1. Declare and initialize the List or Set as you normally would
  2. Between the end of the constructor’s closing parenthesis and the semi-colon, add two braces
  3. Use the add() method to put new class instances into the collection class
  4. When finished, add two closing braces before the semi-colon

It’s probably easier to understand when you see the double brace initialization in action.

Double brace initialization example

The example above implemented with double brace Java syntax would look as follows:

ArrayList<String> list = new ArrayList<String>() {{
  add("alpha");
  add("beta");
  add("charlie");
  add("devo");
}}

The change isn’t earth shattering. But it is notable.

Compared to before, Java’s double brace initialization is more concise, it is less verbose, and it creates code that is more readable and maintainable for developers who will work on the code in the future.

If you need to seed a Set or List in Java, make your life just a little bit easier, and take advantage of Java’s double brace initialization feature.

Java User Input Made Easy

Learn the easiest ways to handle user input in Java, and format any console output with printf.

SearchAppArchitecture
SearchSoftwareQuality
SearchCloudComputing
SearchSecurity
SearchAWS
Close