在构造函数中初始化 int 数组

我有一门课,在那门课上我有这个:

 //some code
private int[] data = new int[3];
//some code

然后在我的构造函数中:

public Date(){
data[0] = 0;
data[1] = 0;
data[2] = 0;
}

如果我这样做,一切都没问题。默认数据值被初始化,但如果我这样做:

public Date(){
int[] data = {0,0,0};
}

上面写着:

Local variable hides a field

为什么?

在构造函数中初始化数组的最佳方法是什么?

554119 次浏览

why not simply

public Date(){
data = new int[]{0,0,0};
}

the reason you got the error is because int[] data = ... declares a new variable and hides the field data

however it should be noted that the contents of the array are already initialized to 0 (the default value of int)

in your constructor you are creating another int array:

 public Date(){
int[] data = {0,0,0};
}

Try this:

 data = {0,0,0};

NOTE: By the way you do NOT need to initialize your array elements if it is declared as an instance variable. Instance variables automatically get their default values, which for an integer array, the default values are all zeroes.

If you had locally declared array though they you would need to initialize each element.

The best way is not to write any initializing statements. This is because if you write int a[]=new int[3] then by default, in Java all the values of array i.e. a[0], a[1] and a[2] are initialized to 0! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.

private int[] data = new int[3];

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

In your constructor it should be:

data = new int[]{0, 0, 0};

You could either do:

public class Data {
private int[] data;


public Data() {
data = new int[]{0, 0, 0};
}
}

Which initializes data in the constructor, or:

public class Data {
private int[] data = new int[]{0, 0, 0};


public Data() {
// data already initialised
}
}

Which initializes data before the code in the constructor is executed.

This is because, in the constructor, you declared a local variable with the same name as an attribute.

To allocate an integer array which all elements are initialized to zero, write this in the constructor:

data = new int[3];

To allocate an integer array which has other initial values, put this code in the constructor:

int[] temp = {2, 3, 7};
data = temp;

or:

data = new int[] {2, 3, 7};