Java Initialize an int array in a constructor

后端 未结 6 1201
失恋的感觉
失恋的感觉 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条回答
  •  猫巷女王i
    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)

提交回复
热议问题