Integer比较当>128要用equals不能用==

当Integer id值超过127时,使用`==`比较可能导致错误结果,返回false。原因是Integer对象在-128到127范围内会使用缓存,而超出该范围则会新建对象。因此,为了正确比较Integer对象的值,应该使用`equals`方法。

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

Integer比较当>128要用equals不能用==

问题描述:
之前在项目中遇到过一个问题,比较两个id是否相等,用的是进行判断,数据量不大的时候是没有问题的,随着数据量的增加,id值超过127问题就来了,两个相同的超过127的id值用比较返回false,通过百度搜索发现要用equals比较。
通常到了这一步可能就不会再往下深究了,可是到面试的时候就彻底凉凉了,所以凡事还是多问个为什么。

1,先来看==和equals的区别

==对于基本数据类型比较的是值,而对于引用类型比较的就是引用的地址,即两个引用是否指向同一个对象实例

public class Test {

    public static void main(String[] args) {

        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a+b));
        System.out.println(c.equals(a+b));
        System.out.println(g == (a+b));
        System.out.println(g.equals(a+b));
    }
}
执行结果:
true
false
true
true
true
false

equals 对于没有重写equals方法的引用类型的比较和==是一样的,只是String,包装类等重写了equals方法,所以按重写后的规则进行比较,比较的是对象指向的内容是否相等;对于基本数据类型则没有equals方法

2,原因
查看Integer源码发现,Integer内部有一个静态变量缓存池IntegerCache,里面声明了一个Integer[]数组,范围-128——127

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 e = 321 ,其实就是调用Integer的valueOf(int i)方法进行自动装箱

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

如果范围不超过-128——127,则从IntegerCache中直接获取Integer对象,如果不在范围内则会new一个新的Integer对象。

根据==和equals区别可以得到为什么要用equals比较了。

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值