使用初始化块有什么好处? [英] What is the advantage of using initialization blocks?
问题描述
我知道初始化块在首次加载类(静态初始化块)或创建实例(实例初始化块)时运行.
I know that Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block).
class SmallInit {
static int x;
int y;
static { x = 7 ; } // static init block
{ y = 8; } // instance init block
}
但是,当我们可以这样做的时候,这样做有什么特殊的好处?
But what is the special benefit of this, when we can do it like this:
class SmallInit {
static int x = 7;
int y = 8;
}
推荐答案
One nice thing about instance initialization blocks is that they make the Double Brace Initialization pattern possible.
代替此:
Set<String> names = new HashSet<String>();
names.add("Peter");
names.add("Paul");
names.add("Mary");
您可以执行以下操作:
Set<String> names = new HashSet<String>() {{
add("Peter");
add("Paul");
add("Mary");
}};
第一个括号创建一个匿名内部类;第二个启动实例初始化程序块. (请注意,这意味着names
是HashSet
的匿名 subclass 的实例,但这通常不是问题.这也意味着该模式仅适用于非最终类.)
The first brace creates an anonymous inner class; the second starts the instance initializer block. (Note that this means names
is an instance of an anonymous subclass of HashSet
, but that's often not an issue. This also means that this pattern only works for non-final classes.)
这在一次性将对象初始化为表达式的情况下特别有用.例如:
This is especially useful in one-off situations where it would be convenient to initialize an object as an expression. For example:
doSomethingToSet(new HashSet<String>() {{
add("Peter");
add("Paul");
add("Mary");
}});
这篇关于使用初始化块有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!