4

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())
        System.out.println("true");
}

IntelliJ IDEA gives me warning 'Unnecessary unboxing' on a.intValue() and b.intValue() and recommend me to simplify code to this:

public void compareMayNull(Integer a, Integer b) {
    if ((a == null ? -1 : a) == b)
        System.out.println("true");
}

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?

Boris
  • 4,944
  • 7
  • 36
  • 69

2 Answers2

6

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-1
compareMayNull(Integer a, Integer b) 

should do other than returning void...

maybe an int will be fine so you can do

(a == null ? -1 : a.compareTo(b)
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97