引言
之前看代碼的時候,發生一個BUG,因爲Integer使用==比較,自己模擬了一個隨機數據模擬測試接口,發現沒有問題,之後發現是==比較的問題。那Integer爲什麼不能用==比較,而應該使用equals?爲什麼大多數測試時發現這樣比較並沒有問題?今天就以這兩個兩個問題爲引,對Integer緩存機制進行一下分析。
測試Integer的緩存機制
IntegerCache類實例:
//Integer緩存成功
Integer a1 = 100;
Integer a2 = 100;
if(a1 == a2) {
System.out.println("a1==a2:" + (a1 == a2));
}
//Integer緩存失效
Integer b1 = 200;
Integer b2 = 200;
if(b1 == b2) {
System.out.println("b1==b2:" + (b1 == b2));
}
輸出顯示:
a1==a2:true
可以發現當數字較大時==判定爲false,不再是同一Integer,我們繼續分析。首先分析一下Integer a1 = 100;的自動裝箱。
自動裝箱
IntegerCacheP實例代碼:
public static void main(String[] args) {
Integer integer = 100;
Integer integer1 = 2000;
}
使用javap -c IntegerCacheP.class對字節碼進行反編譯,看看調用了什麼。內容如下:
Compiled from "IntegerCacheP.java"
public class com.owl.zookeeper.use.integer.IntegerCacheP {
public com.owl.zookeeper.use.integer.IntegerCacheP();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: bipush 100
2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1
6: sipush 2000
9: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
12: astore_2
13: return
}
2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;從這裏可以看出它調用了Integer.valueOf方法對int進行裝箱成Integer。
接下來我們看一下自動Integer.valueOf(int)方法的實現。
Integer緩存實現分析
Integer.valueOf(int)方法實現
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看出當i在一個範圍內時,會從一個Integer[]數組中取出一個Integer對象。所以我們就知道爲什麼某些時候==是不會出錯的。那麼接着我們來分析其實際範圍是多少,合適加載這些緩存。
IntegerCache內部類
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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
可以看出Integer緩存默認範圍是-128<—>127,可以通過IntegerCache.high設置最大的範圍。因爲這部分是static的,所以在加載類是就會初始化Integer緩存,之後只要符合範圍內所有Integer都是來自於這個緩存數組static final Integer cache[]。
總結
可以看出我們在進行Integer值判定時,應使用equals,而不應使用==,這可以避免出現奇怪的錯誤(不在緩存範圍時失效)。