標籤:style blog color for 代碼 div
public static void main(String[] args) { Integer a1 = 1; Integer a2 = 1; Integer b1 = 127; Integer b2 = 127; Integer c1 = 128; Integer c2 = 128; Integer d1 = 321; Integer d2 = 321; System.out.println(a1 == a2); System.out.println(b1 == b2); System.out.println(c1 == c2); System.out.println(d1 == d2);}
結果:
true
true
false
false
原因:
首先我們來看一下JDK源碼是如何?Integer.valueOf()方法的;
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);}
其中IntegerCache是Integer類中的一個內部類,其代碼比較簡單,如下所示:
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); }}
如果傳入的int在[-128~127],那就嘗試看前面的緩衝中有沒有打過包的相同的值,如果有就直接返回,否則就建立一個Integer執行個體。
看到這兒之後,上面的結果就顯而易見了。