【转】Java判断Integer相等-应该这么这样用

发布时间 2023-09-27 05:45:55作者: tc310

先看下这段代码,然后猜下结果:

Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
针对以上结果,估计不少Java小伙伴会跟我一样算错,哈哈!

如果在项目中使用==对Integer进行比较,很容易掉坑。

为什么发生以上结果?
1、执行Integer i1 = 50的时候,底层会进行自动装箱:

Integer i1 = 50;
//底层自动装箱
Integer i = Integer.valueOf(50);
2、再看==操作

==是判断两个对象在内存中的地址是否相等。所以System.out.println(i1 == i2); 和 System.out.println(i3 == i4); 是判断他们在内存中的地址是否相等。

根据猜测应该全是false或者全是true呀,怎么会不同呢?

3、源码底下无秘密

通过翻看jdk源码,你会发现:如果要创建的 Integer 对象的值在 -128 到 127 之间,会从 IntegerCache 类中直接返回,否则才调用 new Integer方法创建。所以只要数值是正的Integer > 127,则会new一个新的对象。 数值 <= 127时会直接从Cache中获取到同一个对象。

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

}
结论
本文简单分析了下Integer类型的==比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals。

同理,Byte、Shot、Long等,也有Cache,各位记得翻看源码!

本篇完结!感谢你的阅读,欢迎点赞 关注 收藏 私信!!!

原文链接:http://www.mangod.top/articles/2023/03/15/1678873359924.html