自动装箱拆箱+包装类的缓存机制(底层代码)

1 自动装箱拆箱原理

  • 装箱:基本数据类型转成对应的包装类
  • 拆箱:包装类转为对应的基本数据类型
  • 原理:Java中装箱和拆箱都是隐式操作,以Integer为例,装箱的时候会自动调用Integer.valueOf()方法,如果是-128至127之间,会从缓存中直接直接复用已经创建好的对象,如果是超过这个范围,调用Integer的构造器造对象;拆箱的时候,会自动调用Integer.intValue()方法,直接返回对应的基本数据类型的值
    在这里插入图片描述
    在这里插入图片描述

2 包装类的缓存机制

  • Java的包装类中,除了float和double之外,都用到了缓存机制来提升性能
  • 底层实现:在包装类的内部声明了静态的内部类,内部类里面封装了包装类类型的数组,这个数组随着类的加载而加载;就相当于提前把常用的包装类对象造好了,如果自动装箱的数据在这个范围内,就直接去数组中复用已经造好的对象,不用每次都new对象了
  • 缓存池范围:Byte、short、Integer、Long范围是-128至127,Character范围是0-127,Boolean类型是True或false
    在这里插入图片描述
    //Integer内部定义了,静态内部类IntegerCache
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[]; // Integer类型数组,存放-128至127之前的Integer对象

        static {
            // 最高限度可以调整,一般都设置为127
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            
            // 提前在数组中new好-128值127之前的Integer对象,方便装箱时直接复用,不用每次new对象
            cache = new Integer[(high - low) + 1];
            int j = low;
            // 超过此范围就需要单独调用构造器
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值