问题描述
{{ ... }}
块在以下代码中是什么意思?
What does {{ ... }}
block mean in the following code?
class X {
private Y var1;
private X() {
Z context = new Z(new SystemThreadPool()) {{
var1 = new Y();
}};
}
}
推荐答案
It's called double curly brace initialization. ( Link removed, archived here)
这意味着您正在创建一个匿名子类,并且双括号内的代码基本上是一个构造函数.它通常用于向集合中添加内容,因为Java用于创建本质上是集合常量的语法有些尴尬.
It means you're creating an anonymous subclass and the code within the double braces is basically a constructor. It's often used to add contents to collections because Java's syntax for creating what are essentially collection constants is somewhat awkward.
所以您可以这样做:
List<String> list = new ArrayList<String>() {{
add("one");
add("two");
add("three");
}};
代替:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
我实际上不喜欢,更喜欢这样做:
I actually don't like that and prefer to do this:
List<String> list = Arrays.asList("one", "two", "three");
因此,在这种情况下它没有多大意义,而对于没有方便助手的Maps来说却没有多大意义.
So it doesn't make much sense in that case whereas it does for, say, Maps, which don't have a convenient helper.
这篇关于新的Class(...){{...}}初始化习惯用法的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!