What is Double Brace initialization in Java?(什么是 Java 中的双大括号初始化?)
问题描述
什么是 Java 中的双括号初始化语法({{ ... }})?
What is Double Brace initialization syntax ({{ ... }}) in Java?
推荐答案
双大括号初始化创建一个从指定类(外大括号)派生的匿名类,并在该类中提供一个初始化块(内大括号).例如
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
   add(1);
   add(2);
}};
请注意,使用这种双括号初始化的效果是您正在创建匿名内部类.创建的类有一个指向周围外部类的隐式 this 指针.虽然通常不是问题,但在某些情况下可能会导致悲伤,例如在序列化或垃圾收集时,请注意这一点.
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
这篇关于什么是 Java 中的双大括号初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是 Java 中的双大括号初始化?
				
        
 
            
        基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				