Java自动装箱和拆箱的实现原理

一、装箱和拆箱

原始类型转换为对象类型就是装箱,反之就是拆箱。
原始类型byte,short,char,int,long,float,double,boolean对应的封装类为Byte,Shor,Character,Integer,Long,Float,Double,Boolean.

二、源码解读

自动装箱时编译器调用valueOf将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。
以Integer的自动装箱为例:

 public static Integer valueOf(int i) {
        //判断i是否在-128和127之间,存在则从IntegerCache中获取包装类的实例,否则new一个新实例
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    //使用亨元模式,来减少对象的创建(亨元设计模式大家有必要了解一下,我认为是最简单的设计模式,也许大家经常在项目中使用,不知道他的名字而已)
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        //静态方法,类加载的时候进行初始化cache[],静态变量存放在常量池中
        static {
            // high value may be configured by property
            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;

            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;
        }

        private IntegerCache() {}
    }

Integer i = 40;相当于调用了Integer.valueOf(40)方法:
首先判断i是否在-128和127之间,如果在,直接从IntegerCache缓存中获取指定数字的包装类;不存在则new出一个新的包装类。
IntegerCache内部实现了一个Integer的静态常量数组,在类加载的时候,执行static静态代码块进行初始化-128到127之间的Integer对象,存到cache数组中。cache属于常量,存放在Java的方法区中。

这就解释了以下的结果:

Integer i = 40;
Integer j = 40;
Integer k = 200;
i == j    为true;
i == k   为false;
Integer i4 = new Integer(40);  
Integer i5 = new Integer(40);  
Integer i6 = new Integer(0); 
i4 == i5   为false,因为直接new,地址不同
i4 == i5+i6  为true,因为涉及到缓存。

Java8种基本类型的自动装箱源码:

 //boolean原生类型自动装箱成Boolean
    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

    //byte原生类型自动装箱成Byte
    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

    //byte原生类型自动装箱成Byte
    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

    //char原生类型自动装箱成Character
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }

    //int原生类型自动装箱成Integer
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

    //int原生类型自动装箱成Long
    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

    //double原生类型自动装箱成Double
    public static Double valueOf(double d) {
        return new Double(d);
    }

    //float原生类型自动装箱成Float
    public static Float valueOf(float f) {
        return new Float(f);
    }

通过源码分析,只有double和float没有使用缓存,每次都是new一个新对象。
使用缓存的策略是因为缓存的这些对象都是经常使用到的,防止每次自动装箱都创建一次对象的实例。

缓存对象的范围:
在这里插入图片描述

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值