Search code examples
javacastingnullpointerexception

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.


Solution

  • I try to avoid casts whenever possible, so I'd rather use the following, which also looks nicer in my opinion:

    Integer.valueOf(8).equals(m.get("null"))