public class CompareDemo { public static void main(String[] args) { int a = 128, b = 128; System.out.PRintln(a == b); // true Integer c = 128, d = 128; System.out.println(c == d); // false System.out.println(c.equals(d)); // true Integer e = -128, f = -128; System.out.println(e == f); // true }}我們在命令行執行一下
1. javac CompareDemo.java
2. javap -c CompareDemo
部分截圖如下:

可以看到在 在執行Integer c = 128, d = 128; 時調用了兩次 Integer.valueOf()函數。
所以語句Integer c = 128 ; 等同于Integer c =Integer.valueOf(128);
Integer d = 128 ;等同于Integer d =Integer.valueOf(128);
我們從源碼中看下這個函數的實現:
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); }很明顯當i >= -128 且 i <= 127 時,我們返回的是緩存中的Integer的對象。
內部類 IntegerCache 定義如下:
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); } }這就解釋了為什么 c == d 返回的為什么是false了, c,d 這里都是對象,== 比較的是引用的地址,
c.equals(d) 才是對象中值的比較。正是因為c,d 的128超出了IntegerCache緩存的范圍,所以c,d
是兩個不同的對象,自然引用地址也不同。
而e , f 的-128 則在緩存的范圍內,故返回的是同一個對象。引用地址相同。
新聞熱點
疑難解答