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?
The last line corresponds to:
Since
compareInt()takes twoIntegerobjects, the two parameters get auto-boxed. During that process, instances ofInteger(n)for small values ofnget 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 comparingIntegerobjects. For further discussion, see https://stackoverflow.com/a/1515811/367273