整数比较值的输出错误 [英] Wrong output for integer comparison values
问题描述
我有以下代码。
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
$ b b
其中正确的输出应为:
false
的实例
false
false
>解决方案
最后一行对应于:
compareInt(100,100)
由于
compareInt()
需要两个Integer
对象,这两个参数自动加入。在此过程中,小于code> nInteger(n)
。换句话说,compareInt()
接收两个对同一个Integer(100)
对象的引用。这是导致最后一次比较评估为true
的原因。
底线是不使用
==
运算符直接比较Integer
对象。有关详情,请参阅 http://stackoverflow.com/a/1515811/367273I have the following code.
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); }
That gives me this output:
false false true
Where the currect output should be:
false false false
Why am I getting the wrong output for the code?
解决方案The last line corresponds to:
compareInt(100, 100);
Since
compareInt()
takes twoInteger
objects, the two parameters get auto-boxed. During that process, instances ofInteger(n)
for small values ofn
get interned. In other words,compareInt()
receives two references to the sameInteger(100)
object. This is what's causing the last comparison to evaluate totrue
.See Using == operator in Java to compare wrapper objects
The bottom line is to not use the
==
operator for directly comparingInteger
objects. For further discussion, see http://stackoverflow.com/a/1515811/367273这篇关于整数比较值的输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!