Java Initialize an int array in a constructor

后端 未结 6 1200
失恋的感觉
失恋的感觉 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: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};
    

提交回复
热议问题