Java经典面试题(装箱,拆箱)一次看懂,终生不忘

题目描述

下面三个输出的值是什么

Integer i  = 10;
Integer j = 10;
System.out.println(i == j); //true 

Integer a = new Integer(10);
Integer b = new Integer(10);
System.out.println(a == b); //false

Integer i2 = 150;
Integer j2 = 150;
System.out.println(i2 == j2);//false 

解题之前

我们大概了解一下装箱和拆箱基本语法

自动装箱即,直接将一个基本类型数据使用引用类型(封装类)表示:(上下两种表述等价)

  Integer i  = 10;
  Integer i = Integer.valueOf(10); 

自动拆箱,将一个封装类型对象使用基本类型直接表示

int n = new Integer(10);
new Integer(10).intValue(); //拆箱,编译器自动处理

首先看 对象a和b,它们是由包装类Integernew出来的对象,而==是判断a和b的地址,其存储原理如下图
在这里插入图片描述
new出来的不同对象,自然地址不相同,最后输出的结果是false

接下来,我们看ij为什么地址一样,而i1j2不一样
我们回到Integer类源码从大概结构来看,利用了一个内部类的操作
在这里插入图片描述
在装箱中编译器调用了Integer中 valueOf()方法,我们在Integer类中定位到此方法

  /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

对此API解释为
在这里插入图片描述
我们一步步去定位Integer类,里面有个IntegerCache 我们上面提到的内部类

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

在IntegerCache类 中创造了一个cache数组,这个数组大小

cache = new Integer[(high - low) + 1];

low 值是固定的-128,high的值是这样来的(注解)

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

现在我们知道了这个数组来历接着回到valueOf()方法

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

我们装箱的时候如果超出了这个cache数组里存放的数值,方法返回一个新对象,所以我们定义一个不在 -128~127这个区间值时,地址则也不一样

总结

包装类Integer在装箱时,会把-127~128间的数装到我们内部数组中,内部cache数组中对应的元素引用到我们的Integer对象,如果包装的数值大于这个区间则会重新new对象.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西伯利亚大熊猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值