문제

public static void mystery(int[] arr) {
    int[] tmp = new int[arr.length];
    tmp[0] = arr[arr.length-1];
    tmp[arr.length-1] = arr[0];
    arr = tmp;
}

int[] a = {2,3,4};
mystery(a);

When I run this, I get that even after calling mystery(a), the value of a is still

a = {2,3,4};

Java arrays are mutable, and all arguments are pass by reference. Since in the method arr points to the memory stored in tmp after the method, why is a unchanged?

도움이 되었습니까?

해결책

In java changing the argument of a method to refer to some other object does not have any effect on the original argument. Therefor a does not point to tmp after the execution of mystery.

To accomplish the swapping your mystery method needs to work on arr directly

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top