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?
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
Initialize Array in Constructor in JavaWe can create an array in constructor as well to avoid the two-step process of declaration and initialization. It will do the task in a single statement. See, in this example, we created an array inside the constructor and accessed it simultaneously to display the array elements.
An array constructor can be used to define only an ordinary array with elements that are not a row type. An array constructor cannot be used to define an associative array or an ordinary array with elements that are a row type. Such arrays can only be constructed by assigning the individual elements.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With