Search code examples
javainitializerdouble-brace-initialize

Java double brace initialization works always?


I know that this code:

Set<String> set = new HashSet<String>() {{
  add("test1");
  add("test2");
}};

is really:

Set<String> set = new HashSet<String>() {
  {//initializer
    add("test1");
    add("test2");
  }
};

The initializer block is being executed before the constructor block. In the above example, add("test1") is called before the constructor being executed. The constructor may be initializing many of the instance fields, so that this class would work. I am wondering why calling .add() before constructor would work? Is there any case that cause an issue?


Solution

  • There is a detail you left out that explains this.

    First of all, let's review steps 3 through 5 of the initialization procedure (summarized):

    3. the superclass constructor is called
    4. the instance initializers are called
    5. the body of the constructor is called

    The detail that you've left out is that your expression is not simply creating a new instance of the HashSet class, it is in fact creating a new instance of an anonymous subclass of HashSet. (I believe this is specified in section 15.9.1.)

    Since you did not declare a constructor, the default constructor is used. But before that, the constructor of the superclass HashSet has completed.

    So, in summary, the HashSet constructor completes before your initializer block runs.