Java Initialize int array in constructor

I have a class and in this 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, everything will be all right. The default values ​​are initialized, but if I do this instead:

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

It says:

 Local variable hides a field 

Why?

What is the best way to initialize an array inside a constructor?

thank

+57
java
Nov 09 '11 at 16:50
source share
6 answers
 private int[] data = new int[3]; 

This already initializes the elements of the array to 0. You do not need to repeat this again in the constructor.

In your constructor, this should be:

 data = new int[]{0, 0, 0}; 
+123
Nov 09 '11 at 16:55
source share
β€” -

You can 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.

+6
Nov 09 '11 at 17:07
source share

why not just

 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 data field

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

+4
Nov 09 '11 at 16:52
source share

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

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

 data = new int[3]; 

To select an integer array that has different initial values, put this code in the constructor:

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

or

 data = new int[] {2, 3, 7}; 
+4
Nov 09 '11 at 17:20
source share

in your constructor you create another int array:

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

Try the following:

  data = {0,0,0}; 

NOTE. By the way, you do NOT need to initialize the elements of the array 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 zeros.

If you have a locally declared array, although you will need to initialize each element.

0
Nov 09 '11 at 16:52
source share

The best way is not to write any initialization statements. This is because if you write int a[]=new int[3] , then by default in Java all values ​​of the array ie a[0] , a[1] and a[2] initialized to 0 ! As for the local variable hiding the field, send all your code so that we can conclude.

0
Nov 09 2018-11-11T00:
source share



All Articles