Integer cache緩存java
下面有一個簡單的關於Integer的實例,但出乎預料的是其輸出結果:
數組
public class IntegerTest2 { public static void main(String[] args){ Integer i1 = 100; Integer i2 = 100; System.out.println(i1 == i2); Integer i3 = 200; Integer i4 = 200; System.out.println(i3 == i4); } }
上面的實例輸出結果爲:true 和 false緩存
這是爲何呢?有點難以想象 ...ide
下面咱們經過查看Integer的源代碼來分析一下(像這種問題也只能經過源代碼來查看分析其緣由);性能
看Integer的valueOf方法,該方法是將int的轉變爲Integer,但當int值大於-128並小於127時,其必須緩存 must cache,並返回的是IntegerCache的cache數組中的值;spa
咱們在看IntegerCache,該類是Integer的一個內部類,它定義了一個靜態的Integer類型的數組,並在靜態塊中將其循環初始化值;code
也就是說,咱們利用Integer得到的大於-128並小於127的對象是,返回的都是緩存起來的對象,並無新生成對象。對象
public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }
JDK的API文檔提示:文檔
public static Integer valueOf(int i)it
若是不須要新的 Integer 實例,則一般應優先使用該方法,而不是構造方法 Integer(int)
,由於該方法有可能經過緩存常常請求的值而顯著提升空間和時間性能。