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的自动装箱解箱

  • 相关阅读:
    SQL Server sql 操作
    MYSQL获取自增ID的四种方法
    Mysql自增字段
    三种JDBC批量插入编程方法的比较
    C3P0连接池使用小结
    数据库连接池 c3p0 demo 代码和分析
    Eclipse 安装对 Java 8 的支持
    Java读取Properties文件的六种方法
    常备软件及必要配置
    HBase-存储-概览
  • 原文地址:https://www.cnblogs.com/cherish010/p/8334711.html
Copyright © 2011-2022 走看看