그래서 두 개의 동일한 배열을 취하고 첫 번째 배열의 첫 번째 값을 두 번째 배열의 마지막 값으로 설정하는 매우 간단한 작업을 수행하려고합니다.배열 예기치 않은 동작
아래 코드는 numberArray
과 을 사용하여 이렇게하려고하는 것입니다. 그러나 코드의 대부분은 내가 이상한 결과를 얻는 이유를 알아 내려고 노력하고 있습니다.
System.out.print("Normal array 1: ");
for (int l = 0 ; l < numberArray.length ; l++){
System.out.print(numberArray[l]);
}
System.out.print("Duplicate array 1: ");
for (int l = 0 ; l < duplicateArray.length ; l++){
System.out.print(duplicateArray[l]);
}
System.out.println();
numberArray[0] = duplicateArray[duplicateArray.length - 1];
System.out.print("Duplicate array 2: ");
for (int l = 0 ; l < duplicateArray.length ; l++){
System.out.print(duplicateArray[l]);
}
System.out.println();
System.out.print("Normal array 2: ");
for (int l = 0 ; l < numberArray.length ; l++){
System.out.print(numberArray[l]);
}
이 출력 :
Normal array 1: 123
Duplicate array 1: 123
Duplicate array 2: 323
Normal array 2: 323
나에게 아무 의미 무슨 심지어 내가 아마 다른 값을 하나의 객체를 설정하고 있지만, 모두가 변화하고 있다는 점이다.
자바의 나의 이해는이입니다
array[x] = array2[y];
//value at index x of "array" now equals value at index y of "array 2"
//however, array2 should not be changed at all since it is just referenced in the above line of code, not mutated
난 정말 간단한 뭔가를 놓치고 있습니까? 나는 이것을 알아 내려고 노력하면서 내 머리를 숙이고 있었다. 어떤 도움이라도 대단히 감사하겠습니다.
편집 :
int[] numberArray = {1, 2, 3};
int[] duplicateArray = numberArray;
이 잘 차이를 수행하지 않아야합니다
나는 그들이 여기에 나의 두 배열의 선언을 제공하도록 요청되었다? 하나의 배열을 다른 배열로 설정해서는 안됩니다.
이 배열에 대한 신고서를 제출해 주실 수 있습니까? 그들은 모두 동일한 객체를 참조합니다. –
두 배열이 메모리의 동일한 배열을 가리키고 있습니다. –
이것은 ** 앨리어싱 **이라고하며 두 배열이 같은 참조를 가리킬 때 발생합니다. – QBrute