挖掘两个Integer对象的swap的内幕

public class SwapTest {

    public static void main(String[] args) throws Exception {
        Integer a = 1, b=2;
        System.out.println("before===="+"a:"+a+"b:"+b);
        swap(a, b);
        System.out.println("after====="+"a:"+a+"b:"+b);
    }

    private static void swap(Integer a, Integer b) throws SecurityException, NoSuchFieldException, Exception {
        Field field= Integer.class.getDeclaredField("value");
        field.setAccessible(true);
        Integer tmp = new Integer(a.intValue());
        field.set(a, b.intValue());
        field.set(b, tmp);
    }

}

运行结果:before====a:1b:2
                 after=====a:2b:1

发掘的要点:

1、包装类引用传递,普通变量是值传递,引用传递传递的是内存地址,不能修改值

public static void main(String[] args) throws Exception {
        Integer a = 1, b=2;
        System.out.println("before===="+"a:"+a+"b:"+b);
        swap(a, b);
        System.out.println("after====="+"a:"+a+"b:"+b);
    }

    private static void swap(Integer m, Integer n) throws SecurityException, NoSuchFieldException, Exception {
        Integer tmp = m;
        m = n;
        n = tmp;
    }

运行结果:before====a:1b:2
                  after=====a:1b:2

2、需要通过反射修改private final变量

3、Integer包装类中的-127-128之类有缓存

4、Integer的自动装箱解箱

原文地址:https://www.cnblogs.com/cherish010/p/8334711.html