zoukankan      html  css  js  c++  java
  • 挖掘两个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的自动装箱解箱

  • 相关阅读:
    POJ Problem 1363 Rails 【栈】
    POJ Problem 3040 Allowance 【贪心】
    ACM 程序对拍
    HDU Problem
    POJ
    HDU Problem
    HDU Problem—2124 Repair the Wall 【贪心】
    HDU Problem 1052 Tian Ji -- The Horse Racing 【贪心】
    POJ Problem Radar Installation 【贪心】
    Beyond Compare和输出文件比较的方法
  • 原文地址:https://www.cnblogs.com/cherish010/p/8334711.html
Copyright © 2011-2022 走看看