Java Initialize an int array in a constructor

后端 未结 6 1189
失恋的感觉
失恋的感觉 2020-12-07 14:11

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:



        
相关标签:
6条回答
  • 2020-12-07 14:51

    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.

    0 讨论(0)
  • 2020-12-07 14:55

    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};
    
    0 讨论(0)
  • 2020-12-07 14:58
    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};
    
    0 讨论(0)
  • 2020-12-07 14:59

    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)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 15:13

    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.

    0 讨论(0)
提交回复
热议问题