JAVA

Java의 배열

ddayunee 2020. 5. 18. 22:02
반응형

Java에서 배열

이번에 java로 코드를 짜다가 int[] position 이라는 값을 hashMap에다가 저장해두려는 의도로 간략히 아래와 같이 코드를 짰습니다.

int[] position = new int[4];
hashMap<Integer, int[]> record = new hashMap<>();
 
for(int i = 0; i < 3; i++) {
  position[0] = i;
  record.put(i, position);
}

이 결과로 원하는 [{0,0,0},{1,0,0},{2,0,0}] 이 아닌 [{2,0,0},{2,0,0},{2,0,0}]이 record에 담기는 것을 알 수 있습니다. 바로 배열이기 때문이죠.

배열이기 때문에 call by Value가 아닌 call by Reference 가 되는 것입니다.

따라서 이때는 아래와 같이 수정하는게 맞습니다.

for(int i = 0; i < 3; i++) {
  position[0] = i;
  int[] tmp = Arrays.copyOf(record, record.length);
  record.put(i, position);
}

Arrays.copyOf의 사용방법은 아래와 같습니다.

Arrays.copyOf(배열, 배열의 길이);
반응형