2014-03-14 42 views
1

我對java中的自動裝箱拆箱感到困惑。請參閱我的以下兩個progarm。Autoboxing wth ++, - java中的運算符

Integer x = 400; 
Integer y = x; 
x++; x--; 
System.out.println((x==y)); 

The output is false. 
I known why the output is false. Because of autoboxing x. 

Integer x = 100; 
Integer y = x; 
x++; x--; 
System.out.println((x==y)); 

The output is true. 
But the program is same as the upper. Why the output is true? 
Please explain me detail. 

非常感謝你。

+0

@TBZ:使用@在給某人發表評論時,會給他們一個通知。 – Keppil

+0

@Keppil:好的。謝謝。 – T8Z

+0

@Keppil只是一個供參考,通知系統現在不管你:) –

回答

1

這是因爲整數-128到127被緩存,所以在第二個例子中x和y指的是相同的Integer實例。

Integer x = 100;   // x refers to cached 100 
x++; 

相當於

int var = x.intValue(); 
var++; 
x = Integer.valueOf(var); // returns cached 100 

見Integer.valueOf(int)的API。

+0

+1,但* *可能會被緩存(但幾乎總是) – Bohemian

+0

我認爲Jon Skeet對Q的回答是這樣的,Dup是更全面的,尤其是在這方面。 –

+0

@Evgeniy Dorofeev:非常感謝你+1 :)。什麼是相同的Integer實例? – T8Z