Meaning of new Class(...){{...}} initialization idiom(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(...){{...}} 初始化习语的含义


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01