我有以下代码:
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.是的
?
最佳答案
对于引用类型,==
检查引用是否相等,即它们是否指向同一个对象。
对于原始类型,==
检查值是否相等。
java.lang.Integer
是一个引用类型。 int
是原始类型。
编辑:如果一个操作数是原始类型,而另一个是拆箱为合适原始类型的引用类型,==
将比较值,而不是引用。
关于java - 比较整数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12547201/