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

Meaning of new Class(...){{...}} initialization idiom(new Class(...){{...}} 初始化习语的含义)

本文介绍了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.

这篇关于new Class(...){{...}} 初始化习语的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:new Class(...){{...}} 初始化习语的含义

基础教程推荐