class Swap { public static void main(String args[]) { Integer a, b; int i,j; a = new Integer(10); b = new Integer(50); i = 5; j = 9; System.out.PRintln(/"Before Swap, a is /" + a); System.out.println(/"Before Swap, b is /" + b); swap(a, b); System.out.println(/"After Swap a is /" + a); System.out.println(/"After Swap b is /" + b); System.out.println(/"Before Swap i is /" + i); System.out.println(/"Before Swap j is /" + j); swap(i,j); System.out.println(/"After Swap i is /" + i); System.out.println(/"After Swap j is /" + j); } public static void swap(Integer ia, Integer ib) { Integer temp = ia; ia = ib; ib = temp; } public static void swap(int li, int lj) { int temp = li; li = lj; lj = temp; } } 上面程序的输出是:
Before Swap, a is 10 Before Swap, b is 50 After Swap a is 10 After Swap b is 50 Before Swap i is 5 Before Swap j is 9 After Swap i is 5 After Swap j is 9
因为swap方法接收到的是引用参数的副本(传值),对他们的修改不会反射到调用代码。
译者注:在传递引用和原始类型时还是有不同的,考虑以下的代码:
class Change { public static void main(String args[]) { StringBuffer a=new StringBuffer(/"ok/"); int i; i = 5; System.out.println(/"Before change, a is /" + a); change(a); System.out.println(/"After change a is /" + a); System.out.println(/"Before change i is /" + i); change(i); System.out.println(/"After change i is /" + i); } public static void change(StringBuffer ia) { ia.append(/" ok?/"); } public static void change(int li) { li = 10; } }
程序的输出为:
Before change, a is ok
After change a is ok ok? Before change i is 5 After change i is 5