[java] Java Initialize an int array in a constructor

I have a class and in that class I have this:

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

Then in my constructor:

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

If I do this, everything is OK. Default data values are initialized but if I instead do this:

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

It says:

Local variable hides a field

Why?

What's the best way to initialize an array inside the constructor?

This question is related to java

The answer is


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};

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.


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.


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.


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)