delver delver - 1 year ago 92
Java Question

Comparing two Integers 'Unnecessary unboxing' warning

I try to compare Integers the next way (for my case, it's good):

public void compareMayNull(Integer a, Integer b) {
if ((a == null ? -1 : a.intValue()) == b.intValue())

IntelliJ IDEA gives me warning 'Unnecessary unboxing' on
and recommend me to simplify code to this:

public void compareMayNull(Integer a, Integer b) {
if ((a == null ? -1 : a) == b)

But I'm little confused, because references will be compared if
a != null
that not best practice as I know. What code should I use?

Answer Source

Because you have a -1 literal which is an int type, a will be auto-unboxed, (if and only if a == null is false else the expression is not evaluated) in the evaluation of the ternary conditional

a == null ? -1 : a;

Then since this expression is of type int, b is also auto-unboxed.

Therefore you can write if ((a == null ? -1 : a) == b), safe in the knowledge that Java will auto-unbox both a and b. So your explicit unboxing via the calls to intValue() is superfluous and your IDE is warning you of this. For the avoidance of doubt a is not auto-unboxed when the expression a == null is evaluated.

Personally I find this to be one of the most pernicious parts of Java. I'd seriously consider writing it the way you originally had it, and tell your IDE to suck it.