前几天看到一个java提供,如下:
public class Test {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.println("swap before:a=" + a + ",b=" + b);
swap(a, b);
System.out.println("swap after :a=" + a + ",b=" + b);
}
private static void swap(Integer a, Integer b) {
// TODO 补全代码
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
在swap方法中补全代码,实现a和b的值进行交换;也许你会:
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.println("swap before:a=" + a + ",b=" + b);
swap(a, b);
System.out.println("swap after :a=" + a + ",b=" + b);
}
private static void swap(Integer a, Integer b) {
// TODO 补全代码
try {
int t = a;
a = b;
b=t;
} catch (Exception e) {
e.printStackTrace();
}
}
}
但这明显是错误的,因为我们都曾学过值传递和引用传递的区别;下面我们看看正确答案:
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
System.out.println("swap before:a=" + a + ",b=" + b);
swap(a, b);
System.out.println("swap after :a=" + a + ",b=" + b);
}
private static void swap(Integer a, Integer b) {
// TODO 补全代码
try {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
int num1 = a.intValue();
int num2 = b.intValue();
valueField.set(a, new Integer(num2));
valueField.set(b, new Integer(num1));
} catch (Exception e) {
e.printStackTrace();
}
}
}
惊不惊喜,意不意外!