关于Integer和int的==比较以及“128陷阱”

这篇博客详细解释了Java中Integer与int使用==比较时的区别。对于int基本类型,==比较的是数值;而对于Integer对象,==比较的是内存地址。在-128到127的范围内,Integer对象会复用缓存的实例,导致==可能返回true。超出这个范围,每次new都会创建新对象,导致不相等。同时,Integer与int比较时会自动拆箱,因此值相等则==返回true。博客还展示了Integer.valueOf()的源码,揭示了这个现象的内在机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于Integer和int的==比较:

对于int基本类型,==比较的是值
对于Integer类型比较的是内存地址,相同的引用:

  1. new一个包装类,地址改变,一定不会相等;
    注意看注释
 public static void main(String[] args) {
        Integer a=100;
        int a1=100;
        System.out.println("a==a1 "+ (a==a1));
  
       Integer b= Integer.valueOf(200);
        Integer bb=200;
        System.out.println("b==bb "+ (b==bb));//非new出来的Integer,如果数在-128到127之间,则是true
        int b2=200;
        System.out.println("b==b2 "+ (b==b2));//Integer与int进行==比较时,不管是直接赋值,还是new创建的对象,只要跟int比较就会拆箱为int类型,所以就是相等的。
        
        Integer c=new Integer(100);
        System.out.println("a==c "+ (a==c));//Integer与new Integer不会相等。不会经历拆箱过程,因为它们存放内存的位置不一样。
        System.out.println("a1==c "+ (a1==c));

    }

在这里插入图片描述

  1. 128陷阱:

在小于127大于-128的时候,自动装箱的是同一个地址存在的数值.大于127时,自动装箱的不在同一个地址,故==比较结果为false

查看valueOf()源码:从源码中可以发现,在 -128—127 之间的数值都存储在有一个catch数组中, 当在-128-127之间进行自动装箱的时候,就直接返回该值在内存当中的相同地址 ,是相同的引用,则用==判断返回true。

  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[];

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值