IT박스

Java 생성자에서 int 배열 초기화

itboxs 2020. 9. 24. 07:40
반응형

Java 생성자에서 int 배열 초기화


나는 수업이 있고 그 수업에는 다음이 있습니다.

 //some code
 private int[] data = new int[3];
 //some code

그런 다음 내 생성자에서 :

public Date(){
    data[0] = 0;
    data[1] = 0;
    data[2] = 0;
}

이렇게하면 모든 것이 정상입니다. 기본 데이터 값이 초기화되지만 대신 이렇게하면 :

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

그것은 말한다 :

Local variable hides a field

왜?

생성자 내부에서 배열을 초기화하는 가장 좋은 방법은 무엇입니까?

감사


private int[] data = new int[3];

이것은 이미 배열 요소를 0으로 초기화합니다. 생성자에서 다시 반복 할 필요가 없습니다.

생성자에서 다음과 같아야합니다.

data = new int[]{0, 0, 0};

다음 중 하나를 수행 할 수 있습니다.

public class Data {
    private int[] data;

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

data생성자에서 초기화 되거나 :

public class Data {
    private int[] data = new int[]{0, 0, 0};

    public Data() {
        // data already initialised
    }
}

data생성자의 코드가 실행되기 전에 초기화 됩니다.


이는 생성자에서 속성과 동일한 이름을 가진 지역 변수를 선언했기 때문입니다.

모든 요소가 0으로 초기화되는 정수 배열을 할당하려면 생성자에 다음을 작성하십시오.

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};

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)


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.


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.

참고URL : https://stackoverflow.com/questions/8068470/java-initialize-an-int-array-in-a-constructor

반응형