How do I use the double brace initialization?

The double brace initialization {{ ... }} is another way for initializing a collection objects in Java. It is offer a simple syntax for initializing a collection object.

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.List;

public class DoubleBraceInitialization {
    public static void main(String[] args) {
        // Creates a list of colors and add three colors of
        // Red, Green and Blue.
        List<String> colors1 = new ArrayList<>();
        colors1.add("Red");
        colors1.add("Green");
        colors1.add("Blue");

        for (String color : colors1) {
            System.out.println("Color = " + color);
        }

        // Creates another list of colors and add three colors
        // using the double brace initialization.
        List<String> colors2 = new ArrayList<>() {{
            add("Red");
            add("Green");
            add("Blue");
        }};

        for (String color : colors2) {
            System.out.println("Color = " + color);
        }
    }
}

What’s actually happened is: the first brace creates an anonymous inner class and the second brace is an initializer block. Due to the need for creating an inner class the use of double brace initialization is considered to be slower.

Because of this performance issue it’s better not to use this technique for your production code, but using it in your unit testing can make your test looks simpler.

Wayan

Leave a Reply

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