【轉】Java判斷Integer相等-應該這麼這樣用

先看下這段代碼,然後猜下結果:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章