如何交换 Integer 的值?
示例1
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class SwapExample {
private static Unsafe unsafe;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Integer a = new Integer(3);
Integer b = new Integer(4);
System.out.println("a=" + a + ",&a=" + addressOf(a));
System.out.println("b=" + b + ",&b=" + addressOf(b));
swap(a, b);
System.out.println("a=" + a + ",&a=" + addressOf(a));
System.out.println("b=" + b + ",&b=" + addressOf(b));
}
private static void swap(Integer a, Integer b) {
Integer tmp = a;
a = b;
b = tmp;
System.out.println("[a=" + a + ",&a=" + addressOf(a));
System.out.println("[b=" + b + ",&b=" + addressOf(b));
}
public static long addressOf(Object o) {
Object[] array = new Object[]{o};
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize) {
case 4:
objectAddress = unsafe.getInt(array, baseOffset);
break;
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return (objectAddress);
}
}
结果:
a=3,&a=3983889842
b=4,&b=3983889844
[a=4,&a=3983889844
[b=3,&b=3983889842
a=3,&a=3983889842
b=4,&b=3983889844
swap 方法中的地址对应的值是没有变化的,只是形参的地址交换了。但是实参的地址没有交换,这个类似值传递。
如果我们在swap中试图改变&a的值看看是否成功
很明显没有修改成功,只是新建了一个对象,这个类似 String
如果一定要修改&a地址中的值呢?
反射:
于是交换的值的代码:
WHY?
Integer tmp = a; 这一步是tmp和a指向同一个地址,我们改了这个地址的值,所以tmp的值也变了。