互换两个Integer对象的值
示例:
public class Demo {
public static void main(String[] args) throws Exception {
Integer a=1;
Integer b=2;
swap(a,b);
System.out.println(a);
System.out.println(b);
}
private static void swap(Integer a, Integer b) throws Exception {
int temp=a.intValue();
Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(a,b.intValue());
value.set(b,temp);
}
}
输出结果却是:
2
2
为什么是这样的结果?
value.set(Object,Object)方法的入参是对象,int会自动装箱,调用valueOf()方法,都知道-128~127的值是存在Integer对象的缓存中的,cache是0~255的一个数组,第一次value.set()方法后缓存中第129位的值已经被改变了,第二次set的时候int自动装箱调用valueOf方法是获取到的值已经是第一次改变后的值,所以是与第一次设置的值一样
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
所以正确的做法是value.set(b,new Integer(temp))