2012-11-20 40 views
1

可能重複:
Weird Java Boxing爲什麼第一個if case打印等於和第二個不等於?

public class example { 
    public static void main(String[] args) { 

     Integer a=127,b=127; 
     if(a==b) 
      System.out.println("Equal"); 
     else 
      System.out.println("Not Equal"); 
     Integer c=128,d=128; 
     if(c==d) 
      System.out.println("Equal"); 
     else 
      System.out.println("Not Equal"); 
    } 

} 

輸出:

Equal 
Not Equal 
+5

的源代碼,他們又來了!它已被問很多次了... – Burkhard

+0

用以下選項之一試用它:'-Djava.lang.Integer.IntegerCache.high = 128'或'-XX:AutoBoxCacheMax = 128'或 '-XX:+ AggressiveOpts ' –

回答

5

基本上整數-127和127之間,以這樣的方式 '緩存',當你使用這些數字你總是指的是相同的號碼 內存,這就是爲什麼你的==的作品。

該範圍之外的任何整數都不會被緩存,因此引用 不相同。

因此,當你試圖比較127與127有隻取得了一個對象 和它的工作的權利,但是當你用128試過出來的 的範圍內,它創建了兩個對象,所以你不能用它們進行比較 ==運算符。

爲此使用.equals()(比較對象引用)method.Please指 this瞭解更多詳情。

Integer c=128,d=128; 
if(c.equals(d)) 
     System.out.println("Equal"); 
    else 
     System.out.println("Not Equal"); 
+1

[語言規格](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7)要求在-128(不包括-127)範圍內自動填寫整數,通過+127被緩存。一個實現也可以自由緩存其他值(在這種情況下+128也可能打印了「Equals」)。 –

+1

@TedHopp你知道他們爲什麼必須被緩存嗎? –

+0

@JanDvorak - 它是Java語言規範所要求的。從[JLS第5.1.7節](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.7):_「如果值爲p盒裝是真的,假的,一個字節或範圍在\ u0000到\ u00f之間的字符,或者在-128到127之間的一個int或短數字,然後讓r1和r2成爲任何兩次裝箱轉換的結果p。r1 == r2始終是這種情況。「_請參閱鏈接瞭解爲什麼這樣做的理由。 –

0

這是因爲在範圍內Integer號碼[-128,127]被存儲在堆。因此,當你比較對象引用而不是對象值,並且Integer a = 127Integer b = 127指向堆中的同一對象時,表達式的求值爲true

Integer值超出這個範圍,你會得到兩個不同的對象,所以參考比較返回false

+1

從技術上講,它們存儲在一個靜態數組中,而不是堆(數據結構;它們存儲在_the_堆(內存區域),雖然) –

0

從Integer.java

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); 
} 
} 

/** 
* Returns a <tt>Integer</tt> instance representing the specified 
* <tt>int</tt> value. 
* If a new <tt>Integer</tt> instance is not required, this method 
* should generally be used in preference to the constructor 
* {@link #Integer(int)}, as this method is likely to yield 
* significantly better space and time performance by caching 
* frequently requested values. 
* 
* @param i an <code>int</code> value. 
* @return a <tt>Integer</tt> instance representing <tt>i</tt>. 
* @since 1.5 
*/ 
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); 
} 
相關問題