Java的装箱拆箱

       简单一点说,装箱就是自动将基本数据类型转换为包装器类型;拆箱就是自动将包装器类型转换为基本数据类型。下面就是对应的基本类型和包装类型:

       int(4字节)--Integer  byte(1字节)--Byte  short(2字节)-- Short   long(8字节)--Long  float(4字节)-- Float

       double(8字节) -- Double  char(2字节)-- Character  boolean(未定)-- Boolean

一:如何实现自动装箱拆箱    

        Integer i = 10;

        int n = i;

       这两句代码的字节码反编译之后我们可以发现:在装箱的时候自动调用的是Integer的valueOf(int)方法。而在拆箱的时候自动调用的是Integer的intValue方法。

       用上面代码再细致的讲解下:

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() {}
    }

         我们可以发现:int值只要在-128和127之间的自动装箱对象都从缓存中获取的,超过就new一个对象

         这个是八个基本类型对应的valueOf方法:

    //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 新的对象,其它的6种基本类型都使用了缓存策略。
    使用缓存策略是因为,缓存的这些对象都是经常使用到的(如字符、-128至127之间的数字),防止每次自动装箱都创建一次对象的实例。
    而double、float是浮点型的,没有特别的热的(经常使用到的)数据的,缓存效果没有其它几种类型使用效率高。

       

       以下是对几个问题的看法和讨论,不正确之处多指教:

       1. 为什么需要自动拆装箱

        个人看法:Java是一个面相对象的编程语言,基本类型并不具有对象的性质,为了让基本类型也具有对象的特征。主要是因为类能够提供必要的方法,例如能实现基本数据类型的数值与可打印字符串之间的转换,另外在某些特定的语法时,例如用泛型的时候,<>里面放的是类,放基本类型报错。所以包装包装,就是包装成一个类,叫包装类。

       2.什么地方可能会自动进行自动拆装箱?

       个人看法:1. 赋值时-- Integer value = 10; // 自动装箱(赋值时) 
                         2. 比较时-- if (value <= 1000) { // 自动拆箱(比较时)
                         3. 算术运算时--int sum = value + 1; // 自动拆箱(算术运算时)
                         4. 方法调用时-- int primitive = value; // 自动拆箱(方法调用时)

       3.自动拆装箱可能会带来那些问题?

       个人看法: 1.有时候我们用==去比较包装类的时候,我们得记住源码中到底是从缓存中获取还是new一个对象,有时哪怕数值一样,但是还是会返回false.

                           2.有时在拆箱的时候产生空指针异常,Integer val = null; int sum = val;这样的代码编译是不会有问题的,但是在运行时会产生空指针异常的,我们需要注意

                           3. 有时我们不小心会用包装类进行for循环,例如 Integer sum = 100; for(int i=0;i<sum;i++) 在i<sum代码会产生拆箱操作,所以这个是需要注意的,对性能是有一定的影响的。

参考:

https://www.cnblogs.com/dolphin0520/p/3780005.html

https://www.jianshu.com/p/0ce2279c5691 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值