質問

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