【发布时间】:2012-09-14 20:38:53
【问题描述】:
我有以下代码:
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. 真的吗?否则,没有任何意义。
-
是的,抱歉,格式将 2 更改为 1。
-
我想补充一点,在 Eclipse 中你可以使用 FindBugs 来捕捉这些错误。