new Class(...){{...}} 初始化习语的含义

下面代码中的{{ ... }}块是什么意思?

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");

所以在这种情况下它没有多大意义,而对于没有方便的助手的地图来说,它没有多大意义.

So it doesn't make much sense in that case whereas it does for, say, Maps, which don't have a convenient helper.

相关文章