我很驚訝第二種情況返回true
。但是,爲什麼在Java Puzzlers他們建議不要混合使用Wrapper類和==
運算符。
看看這個類代碼:
public class RichardInt {
private int value;
public RichardInt(int value) {
this.value = value;
}
}
什麼是下面的結果呢?
RichardInt aa = new RichardInt(100);
RichardInt bb = new RichardInt(100);
System.out.println(aa == bb); // prints false
由於等號運算符==
與對象一起使用時比較引用,因此它會打印爲false。請記住,在Java中,對象是引用類型,而基元(如int
)是值類型。 (注:有人可以讓我知道,如果我錯用「價值型」我有一種感覺,我是誰?)。以下將打印真:
RichardInt aa = new RichardInt(100);
RichardInt bb = aa;
System.out.println(aa == bb); // prints true
...因爲aa
和bb
引用相同的實例RichardInt
。
所以,或許上述行爲在下面的例子中更容易理解......
Intger aaa = new Intger(1000);
Intger bbb = new Integer(1000);
System.out.println(aaa == bbb); // prints false
在較新版本的Java,包裝類(Integer
和Float
和Boolean
等)可以自動箱,這意味着你可以做到以下幾點:
Integer aa = 1000;
// this is a shorthand for...
// Integer aa = new Integer(1000);
但它會導致混亂的行爲,當你嘗試這樣的事情:
Integer aaa = 1000;
Integer bbb = 1000;
System.out.println(aaa == bbb); // prints false
甚至更好,你可以用這樣的難題最終...
// what values of x and y will result in output?
if(!(x<y)&&!(x>y)&&!(x==y)) {
System.out.println("How is this possible?");
}
最後,無論何時處理對象,您都需要使用.equals()
而不是==
。
Integer aaa = 1000;
Integer bbb = 1000;
System.out.println(aaa.equals(bbb)); // prints true
重複:http://stackoverflow.com/questions/3130311/weird-java-boxing – Progman 2010-08-17 20:02:25
是的,這是一種欺騙過很多次。另外http://stackoverflow.com/questions/3131136/integers-caching-in-java-closed,http://stackoverflow.com/questions/1514910/when-comparing-two-integers-in-java-does-auto -unboxing-occurrence – 2010-08-17 20:04:24