Java判斷Integer相等-應(yīng)該這樣用
先看下這段代碼,然后猜下結(jié)果:
Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
針對(duì)以上結(jié)果,估計(jì)不少Java小伙伴會(huì)算錯(cuò)!
如果在項(xiàng)目中使用==對(duì)Integer進(jìn)行比較,很容易掉坑。
為什么發(fā)生以上結(jié)果?
1.執(zhí)行Integer i1 = 50的時(shí)候,底層會(huì)進(jìn)行自動(dòng)裝箱:
Integer i1 = 50;
//底層自動(dòng)裝箱
Integer i = Integer.valueOf(50);
2.再看==操作
==是判斷兩個(gè)對(duì)象在內(nèi)存中的地址是否相等。所以System.out.println(i1 == i2); 和 System.out.println(i3 == i4); 是判斷他們?cè)趦?nèi)存中的地址是否相等。
根據(jù)猜測(cè)應(yīng)該全是false或者全是true呀,怎么會(huì)不同呢?
3.源碼底下無(wú)秘密
通過(guò)翻看jdk源碼,你會(huì)發(fā)現(xiàn):如果要?jiǎng)?chuàng)建的 Integer 對(duì)象的值在 -128 到 127 之間,會(huì)從 IntegerCache 類中直接返回,否則才調(diào)用 new Integer方法創(chuàng)建。所以只要數(shù)值是正的Integer > 127,則會(huì)new一個(gè)新的對(duì)象。數(shù)值 <= 127時(shí)會(huì)直接從Cache中獲取到同一個(gè)對(duì)象。
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() {}
}
結(jié)論
本文簡(jiǎn)單分析了下Integer類型的==比較,解釋了為啥結(jié)果不一致,所以今后碰到Integer比較的時(shí)候,建議使用equals。
同理,Byte、Shot、Long等,也有Cache,各位記得翻看源碼!