Java double brace initialization explained by example

Double brace initialization in Java

Java developers have long desired the ability to quickly initialize contents of a List or Set.

Yet, it’s strange that so many developers are unaware of Java’s relatively new double brace initialization feature.

Historically, when a Java developer seeds list data for tests or assertions, he or she must 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 important.

Compared to before, Java’s double brace initialization makes the more concise, less verbose and 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.