[Java学习笔记]-Java自动装箱和拆箱

之前一直没有特别关注这个问题,以为只有面试时才会用到,直到最近遇到一个大坑,遂总结相关知识,今后面试也好用到

什么是自动装箱拆箱

// 装箱:自动根据数值创建对应的Integer对象
Integer i = 10;
// 拆箱:将包装器类型转换为基本数据类型
Integer n = 10;
int m = i;

自动装箱拆箱的实现

根据反编译结果可知:

  • 装箱自动调用 IntegervalueOf(int) 方法
  • 拆箱自动调用 IntegerintValue 方法

其他的包装器类型如Double、Character也类似
因此自动装箱拆箱可以用一句话总结:装箱过程是通过调用包装器的valueOf 方法实现的,而拆箱过程是通过调用包装器的 xxxValue 方法实现的

缓冲池

先来看一下Integer类中的 Integer.valueOf() 方法的源码实现

	public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

new Integer(123)Integer.valueOf(123) 的区别在于

  • new Integer(123) 每次都会新建一个对象
  • Integer.valueOf(123) 则会使用cache中的对象,多次调用会取得同一个对象的引用

在Java8中,IntegerCache的大小默认为-128 ~ 127

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer 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 a = 100;
Integer b = 100;
System.out.println(a == b); // true

Integer c = 100;
Integer d = 100;
System.out.println(c == d); // true

Integer e = new Integer(100);
Integer f = new Integer(100);
System.out.println(e == f); // false 两对象比较没有进行装箱拆箱

Integer g = 200;
Integer h = 200;
System.out.println(g == h); // false 超出Cache

主要参考资料:
https://www.cnblogs.com/dolphin0520/p/3780005.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值