Integer与Integer,Integer与int的比较(通过源码分析)

public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        int c = 127;
        b.intValue();
        System.out.println((a == b) + " " + (a == c));

        a = 128;
        b = 128;
        c = 128;
        System.out.println((a == b) + " " + (a == c));
    }

利用javap命令对类进行反编译,从而分析其底层原理。

这里写图片描述

以上是第一次println前的反编译结果,可以看到,执行了两次valueOf,也就是,

Integer a = 127;
Integer b = 127;

这两步,执行了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);
 }

 private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
        ...
  }

可以看到,如果 i >= IntegerCache.low && i <= IntegerCache.high,valueOf会返回IntegerCache.cache数组中的数,否则new一个新的对象。
而根据IntegerCache 类的注释:

/**
     * 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.
     */

可以看到,low和high的默认值是-128和127,而high的值可以通过-XX:AutoBoxCacheMax=<size>命令设置。

回到最初的程序,a与b的两次比较,
第一次的值是127,在区间[-128, 127]内,因此a==b的结果是true,
而第二次的值是128,在区间外,因此a==b的结果为false。

继续看反汇编的结果
这里写图片描述

可以看到,a与c比较时,调用了intValue方法,也就是将Integer类转化为int值,再进行比较,因此a与c的两次比较,结果都为true。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值