我有以下代码。
public static void doIntCompareProcess() {
int a = 100;
int b = 100;
Integer c = 200;
Integer d = 200;
int f = 20000;
int e = 20000;
System.out.println(c == d);
compareInt(e, f);
compareInt(a, b);
}
public static void compareInt(Integer v1, Integer v2) {
System.out.println(v1 == v2);
}
这给了我这个输出:
false
false
true
当前输出应该是:
false
false
false
为什么我的代码输出错误?
最后一行对应于:
compareInt(100, 100);
Since compareInt()
需要两个Integer
对象,这两个参数会自动装箱。在此过程中,实例Integer(n)
对于较小的值n
实习。换句话说,compareInt()
收到两次引用同一内容Integer(100)
object。这就是导致最后一次比较评估为true
.
See 在Java中使用==运算符来比较包装对象 https://stackoverflow.com/questions/10149959/using-operator-in-java-to-compare-wrapper-objects
底线是不要使用==
直接比较运算符Integer
对象。如需进一步讨论,请参阅https://stackoverflow.com/a/1515811/367273 https://stackoverflow.com/a/1515811/367273
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)