Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to compare an int with a potentially null Integer in Java?

Map<String,Integer> m;
m = new TreeMap<String,Integer>();

Is it good practice to add the following cast just to avoid the null pointer exception when m.get() is null.

System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false

Alternatively with a prior null check it starts to look a bit ugly.

System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );

Is there a better way to write this? Thanks.

like image 272
Andrew Gallasch Avatar asked Oct 08 '14 13:10

Andrew Gallasch


2 Answers

The == operator doesn't compare values, but references.

You should use the .equals() method, instead, applied to the Integer variable (for which you are sure that is not null and NPE won't be thrown):

Integer eight = 8; //autoboxed
System.out.println(eight.equals(m.get("null")));

This will print false even the m.get("null") returns null.

like image 107
Konstantin Yovkov Avatar answered Oct 05 '22 23:10

Konstantin Yovkov


No, because it will not work. You can't compare two Integer with ==, as that compares references and not the integer values. See more info in this question

You'll need a helper method, such as:

boolean safeIntegerCompare(Integer a, int b)
{
    if (a != null) 
      return a.intValue() == b;
    return false;
}
like image 26
nos Avatar answered Oct 05 '22 22:10

nos