问题
I 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?
回答1:
The last line corresponds to:
compareInt(100, 100);
Since compareInt()
takes two Integer
objects, the two parameters get auto-boxed. During that process, instances of Integer(n)
for small values of n
get interned. In other words, compareInt()
receives two references to the same Integer(100)
object. This is what's causing the last comparison to evaluate to true
.
See Using == operator in Java to compare wrapper objects
The bottom line is to not use the ==
operator for directly comparing Integer
objects. For further discussion, see https://stackoverflow.com/a/1515811/367273
回答2:
Integer values in the primitive byte range -128 to 127 are cached for performance reasons. Since 100 is a value in this range, same object from the cache is returned everytime. For values not in this range are believed to be not required frequently and new Integer object is returned for them. Now in your case, you are comparing the object references and not the values and since 100 is coming from the cache, the arguments in compareInt() are pointing to the same object and hence the comparison equates to true.
来源:https://stackoverflow.com/questions/10596704/wrong-output-for-integer-comparison-values