自动装箱/拆箱

本文解析了Java中Integer类的自动拆箱和装箱现象,重点讲解了127与128比较结果不同的原因,以及Integer类对[-128, 127]的缓存策略。探讨了为何有包装类存在,以及它们在内存中的行为和==运算符的特殊含义。
摘要由CSDN通过智能技术生成
Integer x = null;
System.out.println(2 * x); 

运行结果:

Exception in thread “main” java.lang.NullPointerException

这是因为x在与2进行相乘之前会先进行自动拆箱
即 x.intValue()
因为x是null,所以会引发空指针异常。

对于八大基本类型,他们都有相应的包装类。并且包装类都是用final修饰的,无法再派生子类。
那么为什么会有包装类呢?因为有时需要将基本类型装换为对象。

以下是int的包装类Integer

public final class Integer extends Number implements Comparable<Integer> {
    /**
     * A constant holding the minimum value an {@code int} can
     * have, -2<sup>31</sup>.
     */
    @Native public static final int   MIN_VALUE = 0x80000000;
    ...
    ...
    ...
}

所有的数值基本类型包装类的超类都是Number类(除了Character和Boolean)

以下演示装箱和拆箱
将int类型变换为Integer类型为装箱
相反,将Integer类型转换为int类型的拆箱

		Integer x = 110;
        int t = 110;
        Integer tt = Integer.valueOf(t);//装箱
        int xx = x.intValue();//拆箱

Integer装箱源码

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

Integer拆箱源码

	private final int value;
	
    public int intValue() {
        return value;
    }

看一段代码:

		Integer a1 = 128;
        Integer a2 = 128;
        System.out.println(a1 == a2);

        a1 = 127;
        a2 = 127;
        System.out.println(a1 == a2);

我们都知道 == 比较的是对象在内存中的位置
那么这两个 输出的答案是什么呢?
false
true

为什么会这样呢?
128相比较不相等 肯定是因为在内存中创建了两个新的Integer对象。
127不相等则是因为Integer中的这段代码

    /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

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

可以看出,Integer类一实例化,就会将[-128,127]中所有的数在静态块中进行缓存操作,也就是这个范围内的数已经给你包装好了,你只需要将引用指向这个对象就行了,所以,在比较利用==比较127时,其实比的是用一个对象的两个不同名称的引用罢了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值