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 ?
首先 if-else 打印 false。为什么?
==
检查两个引用是否引用同一个对象,在这种情况下它们不是这样==
检查是false
。你需要使用Integer.equals()
, not ==
:
if (i1.equals(i2){
System.out.println("true");
}else{
System.out.println("false");
}
第二次返回true
==
对于原语使用是正确的:int
是一个原始的。
第三个有真实的
正如所指出的JB Nizet https://stackoverflow.com/users/571407/jb-nizet i2
is unboxed http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html to an int
这使得if
条件两人之间的支票int
基元。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)