Integer类(包装类)的缓存

  • 问题引入

对于包装类,我们都知道自动装箱和自动拆箱功能。笔者以Integer为例,比较Integer两个值大小的时候,我们会使用“==”还是包装类的equals方法呢?如果选择“==”比较的伙计要注意了…..

要说明的是-128到127之间的数据用两种的方法是没有问题的,但是这个范围之外就会有差异了,结果会不同。

  • 小demo
public class IntegerCachDemo {

    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;

        System.out.println(a == b);
        System.out.println(a.equals(b));
        System.out.println("-----------");

        Integer c = 128;
        Integer d = 128;

        System.out.println(c == d);
        System.out.println(c.equals(d));
    }

}
//运行结果:
/*
    true
    true
    -----------
    false
    true
*/
  • 结果分析

为什么大于127之后的包装类使用“==”比较的时候就会为false呢,这就是Integer的缓存在作怪(IntegerCache),我们一起来看看源码分析。

  • 源码
Integer c = 128;    //会执行在自动装箱的操作:Integer c = Integer.valueOf(128);

-------------------------------------------------------------------------------
   /**
     *(这里已经注明了该方法只能缓存-128到127的数据)
     * 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) {
        assert IntegerCache.high >= 127;
        /*
            在范围内就调用缓存的数据,如果不在就会直接创建对象
        */
        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[];

        //静态代码块会在类加载的时候完成
        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) {
                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);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                //这里会把-127到128的基本数据类型在类加载的时候,就完成对象的创建。并保存在数组中。
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }
  • 源码分析

通过源码我们可以看见,-127到128这些范围的数据,会在执行valueOf()方法的时候全部创建好对象,使用的时候直接从cache数组中获取就可以了。所以不管你执行几个valueOf()方法(装箱操作),获取的对象都是同一个。所以“==”和equals获取的结果是一样的。但是范围之外,就不会有缓存的对象,每次的valueOf()方法都会创建新的对象。所以“==”比较两个不同的对象显然是false,而equals比较的是包装类对应的基本数据类型。

  • 其他包装器

Boolean、Byte:(全部缓存)

Character:(<= 127缓存)

Short、Long:(-128 到 127缓存)

Float、 Doulbe:(没有缓存)

  • 注意

超出范围的包装类和基本数据类型使用“==”比较的时候,包装类会拆箱操作后,再比较大小。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值