Java在将参数传递给函数时使用按值调用。要交换对象,我们需要使用它们的包装器。请参阅下面的示例-
public class Tester{ public static void main(String[] args) { A a = new A(); A b = new A(); a.value = 1; b.value = 2; //使用对象交换 swap(a,b); System.out.println(a.value +", " + b.value); Wrapper wA = new Wrapper(a); Wrapper wB = new Wrapper(b); //使用对象包装器进行交换 swap(wA,wB); System.out.println(wA.a.value +", " + wB.a.value); } public static void swap(A a, A b){ A temp = a; a = b; b = temp; } public static void swap(Wrapper wA, Wrapper wB){ A temp = wA.a; wA.a = wB.a; wB.a = temp; } } class A { public int value; } class Wrapper { A a; Wrapper(A a){ this.a = a;} }
输出结果
1, 2 2, 1