Java Initialize an int array in a constructor
Solution 1:
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};
Solution 2:
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.