2017-09-06 174 views
1
@Test 
    public void test(){ 
     Map<String, Integer> a = new HashMap<>(); 
     a.put("x", new Integer(0)); 
     Integer i = a.get("x"); 
     a.put("x", i++); 
     i = a.get("x"); 
     a.put("x", i++); 
     i = a.get("x"); 
     a.put("x", i++); 
     System.err.println(i); 
    } 

上面的代碼的輸出是1而不是0我不明白爲什麼。有人可以解釋發生了什麼事嗎? Java的一些字節碼優化導致這種狀態?爲什麼輸出下面的代碼1而不是0?

+1

你增量,所以你爲什麼想到要打印0? – tkausl

+1

請使用調試器。這是瞭解代碼片段工作原理的有效方法。 –

回答

4

因爲i++返回i遞增之前i。見我的評論:

Map<String, Integer> a = new HashMap<>(); 
a.put("x", new Integer(0)); // x=0 
Integer i = a.get("x");  // i=0 
a.put("x", i++);   // x=0, i=1 
i = a.get("x");    // i=0 
a.put("x", i++);   // x=0, i=1 
i = a.get("x");    // i=0 
a.put("x", i++);   // x=0, i=1 
System.err.println(i); 

下面是相關的部分從documentation of unary operators

遞增/遞減運營商可以前(前綴)被應用或之後(後綴)的操作。代碼result++;++result;的結果都會以1遞增。

唯一的區別是前綴版本(++result)評估爲遞增值,而後綴版本(result++)評估爲原始值。

如果您只是執行一個簡單的遞增/遞減,那麼選擇哪個版本並不重要。但是如果你在更大的表達式中使用這個運算符,那麼你選擇的運算符可能會有很大的不同。

1

是的,它應該是一個。最後的聲明是a.put("x", i++);,因此您將0的值存入您的Map,但您隨後增加i。如果你最後的陳述是i = a.get("x");你會得到0

+0

謝謝。得到它了! – user1615664

1

您使用後遞增,因此首先讀取i的值,然後遞增。

@Test 
public void test(){ 
    Map<String, Integer> a = new HashMap<>(); 
    a.put("x", new Integer(0)); 
    Integer i = a.get("x"); // i is 0 
    a.put("x", i++); // x = 0; then i increment 
    i = a.get("x"); // i is reset to 0 
    a.put("x", i++); // x = 0; then i increment 
    i = a.get("x"); // i is reset to 0 
    a.put("x", i++); // x = 0; then i increment 
    System.err.println(i); // i == 1 
} 
0

解釋直列:

@Test 
public void test(){ 
    Map<String, Integer> a = new HashMap<>(); 
    a.put("x", new Integer(0)); // Store Integer(0) 
    Integer i = a.get("x");  // Get it 
    a.put("x", i++);   // Unbox it, rebox it, store it again (still 0); increment it afterward 
    i = a.get("x");    // Same again 
    a.put("x", i++);   // ... 
    i = a.get("x");    // ... 
    a.put("x", i++);   // Unbox it, rebox it, store it again (still 0); increment it afterward 
    System.err.println(i);  // Show it; contains the *incremented* value 
} 

由於存儲的值始終爲0,你得到它在年底增加它,你最終以1

0

讓我們通過這個一步一步:

Integer i = a.get("x"); 

i是0

a.put("x", i++); 

地圖中的「x」不會更改,因爲您將其設置爲i(= 0)並在設置後增加。

i = a.get("x"); 

,我再次得到,因爲依然什麼存儲在「X」

a.put("x", i++); 

同樣的事情上面這就是唯一的「X」設置爲0

後設置爲0,我被設置爲一
i = a.get("x"); 

I = 0

a.put("x", i++); 

現在我是1,您打印

System.err.println(i); 
0

你的最後一句話我增加1個產生的I = 1

相關問題