我有以下代碼:比較整數對象
public class Test {
public static void main(String[] args) {
Integer alpha = new Integer(1);
Integer foo = new Integer(1);
if(alpha == foo) {
System.out.println("1. true");
}
if(alpha.equals(foo)) {
System.out.println("2. true");
}
}
}
輸出如下:
2. true
然而改變Integer object
到int
的類型會產生不同的輸出,例如:
public class Test {
public static void main(String[] args) {
Integer alpha = new Integer(1);
int foo = 1;
if(alpha == foo) {
System.out.println("1. true");
}
if(alpha.equals(foo)) {
System.out.println("2. true");
}
}
}
新產出:
1. true
2. true
這是怎麼回事?爲什麼第一個示例代碼沒有輸出1. true
?
你確定第一個輸出不是2.是真的嗎?否則,沒有任何意義。 – ILMTitan
是的,對不起,格式化將2更改爲1. –
可能的重複:[比較Java中的兩個整數是否會自動取消裝箱?](http://stackoverflow.com/q/1514910/1164465) –