[英]Initializing a java array
Recently, I found that an array can be initialize as follows: 最近,我发现可以按以下方式初始化数组:
private static int[] _array = new int[4];
// An arbitrary amount of code
{
_array[0] = 10;
_array[1] = 20;
_array[2] = 30;
_array[3] = 40;
}
What is this form of initialization called? 这种初始化形式叫什么? What are its limitations?
有什么限制?
This is instance member initialization using an initializer block , and it looks a lot like static initialization which would prefix that block with the word static
. 这是使用构造器块进行实例成员初始化,看起来很像静态初始化,它将用“
static
”一词作为该块的前缀。
Its limitations would match that of any constructor as the Java compiler copies initializer blocks into every constructor. 当Java编译器将初始化程序块复制到每个构造函数中时,它的限制将与任何构造函数的限制匹配。 Therefore, this approach can be used to share a block of code between multiple constructors.
因此,该方法可用于在多个构造函数之间共享代码块。
It is initialization block and regarding to documentation : 它是初始化块,关于文档 :
The Java compiler copies initializer blocks into every constructor.
Java编译器将初始化程序块复制到每个构造函数中。 Therefore, this approach can be used to share a block of code between multiple constructors
因此,该方法可用于在多个构造函数之间共享代码块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.