This syntax is called Java’s Dynamic Initialization Block.
It is a code snippet enclosed in curly brackets within a class and is automatically called when the class is instantiated.
For example:
class Person {
{System.out.print(123);}
}
Then calling new Person()时就会打印出123.
As for the code in your question, it’s just that the dynamic initialization block is placed in an anonymous class, so it looks a bit strange and hard to understand. However, after all, anonymous classes are also classes, so they are legal. The result is that when the anonymous class is instantiated, that code is executed and several elements are put into the collection, which is equivalent to initializing the collection.
As for which version of Java it was first supported, I can’t remember clearly, but it is estimated that it has been supported for a long time, and it should be supported since Java 5.
Finally, initializing a collection in this way looks like black magic.
In addition, you can also check static initialization block and compare their differences.
The curly brackets are not anonymous inner classes, but construction code blocks, which seem to be executed before the construction method (I don’t remember clearly). I regard it as the same thing as the construction method.
This syntax is called Java’s Dynamic Initialization Block.
It is a code snippet enclosed in curly brackets within a class and is automatically called when the class is instantiated.
For example:
Then calling
new Person()
时就会打印出123
.As for the code in your question, it’s just that the dynamic initialization block is placed in an anonymous class, so it looks a bit strange and hard to understand. However, after all, anonymous classes are also classes, so they are legal. The result is that when the anonymous class is instantiated, that code is executed and several elements are put into the collection, which is equivalent to initializing the collection.
As for which version of Java it was first supported, I can’t remember clearly, but it is estimated that it has been supported for a long time, and it should be supported since Java 5.
Finally, initializing a collection in this way looks like black magic.
In addition, you can also check static initialization block and compare their differences.
The curly braces inside are initialization blocks, which will be executed between constructor calls during new
The curly brackets are not anonymous inner classes, but construction code blocks, which seem to be executed before the construction method (I don’t remember clearly). I regard it as the same thing as the construction method.