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?