I have recently found what appears to me to be a new syntax for statically initializing an ArrayList:
new ArrayList<String>() {{
add("first");
add("second");
}};
My question is, what is really happening there? Is that a shortcut for defining a static block (I thought it would need the static
keyword)? Or just a way to define a default constructor? Something else? What version of Java did this become valid?
An explanation plus a link to further reading would be greatly appreciated.
edit: My test class for showing whether initializer block executes before or after the constructor is below. Results show that initializer blocks execute before the other constructor code:
import org.junit.Test;
public class InitializerBlockTest {
class InitializerTest {
{
System.out.println("Running initalizer block");
}
public InitializerTest() {
System.out.println("Running default constructor");
}
}
class SubClass extends InitializerTest {
{
System.out.println("Running subclass Initializer block");
}
public SubClass() {
System.out.println("Running subclass constructor");
}
}
@Test
public void testIt() {
new SubClass();
}
}
Output:
Running initalizer block
Running default constructor
Running subclass Initializer block
Running subclass constructor