Initializing a java array
Recently, I found that an array can be initialize as follow开发者_开发知识库s:
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
.
Its limitations would match that of any constructor as the Java compiler copies initializer blocks into every constructor. 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. Therefore, this approach can be used to share a block of code between multiple constructors
I've answered yesterday in similar post here
精彩评论