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(...){{...}} 初始化习语的含义
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
