Search code examples
javainitializationdouble-brace-initialize

Meaning of new Class(...){{...}} initialization idiom


What does {{ ... }} block mean in the following code?

class X {

    private Y var1;

    private X() {
        Z context = new Z(new SystemThreadPool()) {{
            var1 = new Y();
        }};
    }

}

Solution

  • It's called double curly brace initialization. (EDIT: Link removed, archived here)

    It means you're creating an anonymous subclass and the code within the double braces is basically a constructor. It's often used to add contents to collections because Java's syntax for creating what are essentially collection constants is somewhat awkward.

    So you might do:

    List<String> list = new ArrayList<String>() {{
      add("one");
      add("two");
      add("three");
    }};
    

    instead of:

    List<String> list = new ArrayList<String>();
    list.add("one");
    list.add("two");
    list.add("three");
    

    I actually don't like that and prefer to do this:

    List<String> list = Arrays.asList("one", "two", "three");
    

    So it doesn't make much sense in that case whereas it does for, say, Maps, which don't have a convenient helper.