Integer原始碼,為什麼快取範圍在【-128—+127】?
阿新 • • 發佈:2019-02-09
public final class Integer extends Number implements Comparable<Integer>
Integer是final型別的,表示不能被繼承,同時實現了Number類,並實現了Comparable介面;java中資料型別可以分為兩類,一種的基本資料型別,一種是引用資料型別。
基本資料型別的資料不是物件,所以對於要將資料型別作為物件來使用的情況,java提供了相對應的包裝類。
int是基本資料型別,integer是引用資料型別,是int的包裝類。
自動裝箱的過程:引用了valueOf()的方法
assertion就是在程式中的一條語句,它對一個boolean表示式進行檢查,一個正確程式必須保證這個boolean表示式的值為true;如果該值為false,說明程式已經處於不正確的狀態下,系統將給出警告並且退出。一般來說,assertion用於保證程式最基本、關鍵的正確性。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); }
java內部為了節省記憶體,IntegerCache類中有一個數組快取了值從-128到127的Integer物件。當我們呼叫Integer.valueOf(int i)的時候,如果i的值時結餘-128到127之間的,會直接從這個快取中返回一個物件,否則就new一個新的Integer物件。
即:當我們定義兩個Integer的範圍在【-128—+127】之間,並且值相同的時候,用==比較值為true;
當大於127或者小於-128的時候即使兩個數值相同,也會new一個integer,那麼比較的是兩個物件,用==比較的時候返回false
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) -1); } 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() {} }
IntegerCache是Integer的內部類,用來將-128——high之間的物件進行例項化
這邊固定了快取的下限,但是上限可以通過設定jdk的AutoBoxCacheMax引數調整,自動快取區間設定為[-128,N];
IntegerCache 不會有例項,它是 private static class IntegerCache,在 Integer 中都是直接使用其 static 方法