Integer i1= new Integer(9);
Integer i2= new Integer(9);
if(i1==i2){
System.out.println("true");
}else{
System.out.println("false");
}
int i3=9;
int i4=9;
if(i3==i4){
System.out.println("true");
}else{
System.out.println("false");
}
if(i3==i2){
System.out.println("true");
}else{
System.out.println("false");
}
在上面的代码中,首先 if-else 打印 false,为什么?但是当第二个返回 true 并且第三个也有 true 时。我认为包装类(如 double、boolean、char)无法比较 True?
最佳答案
First if-else print false. Why?
==
检查两个引用是否指向同一个对象,在这种情况下它们不是,所以 ==
检查为 false
。您需要使用 Integer.equals()
,而不是 ==
:
if (i1.equals(i2){
System.out.println("true");
}else{
System.out.println("false");
}
Second return true
==
用于原语是正确的:int
是原语。
third have true
正如 JB Nizet 指出的那样i2
是 unboxed到 int
,它使 if
条件成为两个 int
原语之间的检查。
关于Java 整数在比较两个整数时返回奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9429185/