public class JavaIntegerCache { public static void main(String... strings) { Integer integer1 = 3; Integer integer2 = 3; if (integer1 == integer2) System.out.println("integer1 == integer2"); else System.out.println("integer1 != integer2"); Integer integer3 = 300; Integer integer4 = 300; if (integer3 == integer4) System.out.println("integer3 == integer4"); else System.out.println("integer3 != integer4"); } }
== 比較的是對象引用,而 equals 比較的是值。所以,在這個例子中,不一樣的對象有不一樣的引用,因此在進行比較的時候都應該返回 false。可是奇怪的是,這裏兩個類似的 if 條件判斷卻返回不一樣的布爾值。java
輸出結果:數組
integer1 == integer2
integer3 != integer4
在 Java 5 中,爲 Integer 的操做引入了一個新的特性,用來節省內存和提升性能。整型對象在內部實現中經過使用相同的對象引用實現了緩存和重用。緩存
上面的規則適用於整數區間 -128 到 +127。性能
這種 Integer 緩存策略僅在自動裝箱(autoboxing)的時候有用,使用構造器建立的 Integer 對象不能被緩存。spa
Java 編譯器把原始類型自動轉換爲封裝類的過程稱爲自動裝箱(autoboxing),這至關於調用 valueOf 方法code
public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) { return IntegerCache.cache[i + (-IntegerCache.low)];
} return new Integer(i); }
在建立新的 Integer 對象以前會先在 IntegerCache.cache 中查找。IntegerCache 類專門來負責 Integer 的緩存。orm
IntegerCache 是 Integer 類中一個私有的靜態類(Integer的嵌套類)。對象
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() {} }
這個類是用來實現緩存支持,並支持 -128 到 127 之間的自動裝箱過程。最大值 127 能夠經過 JVM 的啓動參數 -XX:AutoBoxCacheMax=size 修改。 緩存經過一個 for 循環實現。從小到大的建立儘量多的整數並存儲在一個名爲 cache 的整數數組中。這個緩存會在 Integer 類第一次被使用的時候被初始化出來。之後,就可使用緩存中包含的實例對象,而不是建立一個新的實例(在自動裝箱的狀況下)。blog
實際上在 Java 5 中引入這個特性的時候,範圍是固定的 -128 至 +127。後來在 Java 6 中,最大值映射到 java.lang.Integer.IntegerCache.high,可使用 JVM 的啓動參數設置最大值。選擇這個 -128 到 127 這個範圍,是由於這個範圍的整數值是使用最普遍的。 在程序中第一次使用 Integer 的時候也須要必定的額外時間來初始化這個緩存。內存
這種緩存行爲不只適用於Integer對象。咱們針對全部整數類型的類都有相似的緩存機制。
有 ByteCache 用於緩存 Byte 對象
有 ShortCache 用於緩存 Short 對象
有 LongCache 用於緩存 Long 對象
有 CharacterCache 用於緩存 Character 對象
Byte,Short,Long 有固定範圍: -128 到 127。對於 Character, 範圍是 0 到 127。除了 Integer 能夠經過參數改變範圍外,其它的都不行。