3

I saw this code in some places.

new ArrayList<String>(){{
   add("A");
   add("B");
}}

And how should I interpret this code? Someone says this is Instance Initializer. However, in my understanding about Instance Initializer it is used in a class to avoid a repeatment especially in its constructer. That means

public class Test1 {
    int number;

    public Test1() {
        System.out.println("1");
        this.number = 1;
    }

    public Test1(int i) {
        System.out.println("1");
        this.number = i;
    }
}

is normally worse than

public class Test2 {
    int number;

    {System.out.println("1");}

    public Test2() {
        this.number = 1;
    }

    public Test2(int i) {
        this.number = i;
    }
}

So, I thought Instance Initializer in Java was attributed to a specific class, but maybe many people use such Instance Initializer in the way I showed first. And in the way the initializer doesn't belong to a certain class. So I am a little bit confused. Can anyone give any good explanation about first code?

Kazuya Tomita
  • 667
  • 14
  • 34
  • 1
    See [Double-Brace Initialization](http://www.c2.com/cgi/wiki?DoubleBraceInitialization) – qxz Dec 17 '16 at 05:14
  • 1
    The first code is actually Double brace initialization. And it is creating an anonymous class i.e. outer braces, and inner braces is the initializer block. I hope this the simplest explanation but it is considered to be anti pattern refer to http://javarevisited.blogspot.com/2015/10/what-is-double-brace-initialization-in-java-example-anti-pattern.html – David Dec 17 '16 at 05:18
  • Thanks, I understand – Kazuya Tomita Dec 18 '16 at 03:40

0 Answers0