List<String> list = new ArrayList<String>(){
{
add("hello");
remove(0);
}
};
map = new HashMap<String, Object>(){
{
put("name","123");
}
};
请问这个语法是来自 Java 几?他的原理又是什么?一个大括号我知道是匿名内部类,但是里面的大括号不知道是什么意思??
PHPz2017-04-18 09:24:24
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.
巴扎黑2017-04-18 09:24:24
The curly braces inside are initialization blocks, which will be executed between constructor calls during new
黄舟2017-04-18 09:24:24
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.