int与Integer的区别?==判断时的情况?

    public static void main(String[] args) {
        Integer i1 = 127;
        Integer i2 = 127;
        Integer i3 = 128;
        Integer i4 = 128;
        int i5 = 127;
        // Integer相同值的比较
        System.out.println(i1 == i2);// t
        System.out.println(i1 == i5);// t自动拆箱
        // Integer超出127的数,是否同一对象
        System.out.println(i1 == i2);// t
        System.out.println(i3 == i4);// f 否


        /**
         * 查看Integer.valueOf()
         *         public static Integer valueOf(int i) {
         *             if (i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high)
         *                 return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)];
         *             return new Integer(i);
         *         }
         *
         *         Integer.IntegerCache.low
         *         static final int low = -128;
         *         assert IntegerCache.high >= 127;
         */

    }

总结:
int是基本数据类型,Integer是int的包装类。
二者在做==运算时,Integer会自动拆箱为int类型,然后再进行比较。届时,如果两个int值相等则返回true,否则就返回false

另外,查看Integer.valueOf()源码可以看到,当在[-128,127]时,Integer不会new一个对象出来,而是指向原有的地址

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值